G Boggs
G Boggs

Reputation: 391

MATLAB Coder giving out-of-bounds error for struct

I am trying to MEX some code by using MATLAB's coder toolkit. The code initially had cell arrays in it which is not handled by the coder at the moment, so I decided to use structs in compensation for that.

My issue is that the size of the struct is not fixed, and herein lies the problem. What I have essentially is this:

Temp= struct('a',"some variable");
for i = 2:x
    Temp(j).('a') = Temp(i-1).('a')*Temp(1).('a');
end

In the command window of MATLAB, this would be completely acceptable, however when trying to build the MEX file, it throws this error:

Index expression out of bounds. Attempted to access element 2. The valid range is 1-1.

Is there a way to fix this, or is there another solution to 'cell array' like structures that the coder will allow?

Upvotes: 0

Views: 421

Answers (1)

ThP
ThP

Reputation: 2342

You can use repmat:

MyStruct = repmat(Temp,1,N);

where N is a constant (i.e. hard-coded, not data-dependent).
Then, if you wish,

for i=2:N
    MyStruct(i).a = MyStruct(i-1).a*MyStruct(1).a;
end

No need for MyStruct(i).('a')

Upvotes: 2

Related Questions