Matlab coder - Expected a scalar. Non-scalars are not supported in IF or WHILE

aah134 picture aah134 · Sep 9, 2013 · Viewed 7.7k times · Source

I have the following matlab code v is an array of one dimention.

v = getV(x,y,z);
if isempty(v)
    fail_code = 1;
elseif max(v) <= vmax % <============== error is here
    fail_code = 0;
    vplus = max(v);
else
    vplus = vmax;
end

this working fine, however when I try to convert it into a c code in matlab coder I get the following error: Expected a scalar. Non-scalars are not supported in IF or WHILE statements, or with logical operators. Instead, use ALL to convert matrix logicals to their scalar equivalents.

I am not fully familiar with matlab data types, maybe why I am missing something.

Answer

Sam Roberts picture Sam Roberts · Sep 9, 2013

I would put:

elseif all(max(v) <= vmax)

or

elseif max(v(:)) <= vmax

In MATLAB, if test can pass even if test is not a scalar. If test is an array of logicals, it will pass if all the elements are non-zero.

However, that is not supported by MATLAB Coder when converting to C. So, you would need to explicitly ensure that you get a scalar, either by inserting an all, or comparing v to its maximum as a vector.