0

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?

0

1 Answer 1

2

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')

Sign up to request clarification or add additional context in comments.

6 Comments

+1 here are some relevant links to docs: Define Arrays of Structures for Code Generation, Index Substructures and Fields. Any way, it seems to me that the entire structure could be replaced with a regular numeric array
@Amro: For the simple example the OP provided, I agree.
@ThP That worked thanks! I now have another problem though. Some of the variables I am trying to store in struct are complex. It now comes up with the error saying: "Cannot assign a complex value into a non-complex location." Is there a way to fix this?
@GBoggs: try initializing with a complex constant when you first create the structure, so something like: Temp = struct('a',complex(0,0));. See: Code Generation for Complex Data
@GBoggs: See this page: Diagnose and Fix Variable-Size Data Errors. Also read the section in the docs that explains variable-size data.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.