When generating C code using MATLAB Coder, the behaviour is different when an if
happens in body of another if
or in its else
section. The following case easily creates C code with output having size 5x5:
function y = foo1(u)
if u > 0
y = zeros(2,2);
else
y = zeros(5,5);
end
Now this one works as well
function y = foo2(u,v)
if u > 0
y = zeros(2,2);
else
y = zeros(5,5);
if v > 0
y = 2 * y;
end
end
But this one fails to generate code, complaining about size mismatch:
function y = foo3(u,v)
if u > 0
y = zeros(2,2);
if v > 0
y = 2 * y;
end
else
y = zeros(5,5);
end
Here is the output in command-line:
>> codegen foo1.m -args {0}
>> codegen foo2.m -args {0,0}
>> codegen foo3.m -args {0,0}
??? Size mismatch (size [2 x 2] ~= size [5 x 5]).
The size to the left is the size of the left-hand side of the assignment.
Error in ==> foo3 Line: 8 Column: 5
Code generation failed: Open error report.
Error using codegen (line 144)
I have seen this behaviour in MATLAB R2013b and R2015a.
coder.varsize('y',[5,5])
specifies[5 5]
as an upper bound for the variable size of the matrix. It's also possible to specify one or more dimensions as fixed and others as variable sized -- this and more in the documentation page linked in the answer. – Brickbat