Codegen with dynamic field names
9 views (last 30 days)
Show older comments
I'm trying to compile a mex-file from my m-code. I've problems in the following lines
Atm = sys.A0;
Btm = sys.B0;
Ctm = sys.C0;
Dtm = sys.D0;
for i = 1:np
Atm = Atm+sys.(['A',sprintf('%.0f',i)]) * p(i,t);
Btm = Btm+sys.(['B',sprintf('%.0f',i)]) * p(i,t);
Ctm = Ctm+sys.(['C',sprintf('%.0f',i)]) * p(i,t);
Dtm = Dtm+sys.(['D',sprintf('%.0f',i)]) * p(i,t);
end
which returns the error '??? Non-constant expression or empty matrix'.
The variable sys is a structure with field names sys.A0, sys.A1,..., sys.A[np], sys.B0, ..., sys.D[np], sys.np. Where np may vary from case to case and the variables sys.A[i],...,sys.D[i] are 2-D matrices. The variable p is a matrix of size np X m. I compile the code for a fixed sized variable sys and p, with
codegen errAndJac -args {u,p,y,sys}
My problem seems the following. The code generation cannot handle ['A',sprintf('%.0f',i)] to locate a certain matrix. I've also tried to first pre locate a variable iA = char('A0',...,'A[np]') and then use sys.(iA(i,:)), which resulted in the same error.
An alternative and/or solution will be highly appreciated. Thanks in advanced. Attached is the function to compile and an example of my variables.
0 Comments
Accepted Answer
Geoff Hayes
on 6 Nov 2014
Pepjin - why not just combine all of your (for example) AX fields of the sys struct into one three-dimensional field? In your variableExample.mat, the A0, A1, and A2 fields are of the same 10x10 dimension, so just create A as
sys.A = zeros(10,10,3);
sys.A(:,:,1) = A0;
sys.A(:,:,2) = A1;
sys.A(:,:,3) = A2;
If you do this for B, C and D, then your above code becomes
Atm = sys.A(:,:,1);
Btm = sys.B(:,:,1);
Ctm = sys.C(:,:,1);
Dtm = sys.D(:,:,1);
for i = 1:np
Atm = Atm+sys.A(:,:,i+1) * p(i,t);
Btm = Btm+sys.B(:,:,i+1) * p(i,t);
Ctm = Ctm+sys.C(:,:,i+1) * p(i,t);
Dtm = Dtm+sys.D(:,:,i+1) * p(i,t);
end
This way you avoid having to access the the dynamic fields within your struct.
More Answers (0)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!