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

StackOverflow https://stackoverflow.com/questions/18700944

  •  28-06-2022
  •  | 
  •  

Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

Why not follow the advice within the error-message and try:

elseif all(max(v) <= vmax)

In your special case the all() might be superfluous, but I assume that the coder tries to respect the possibility that the comparison could in principle result in an array.

You probably want to test for v being a vector with isvector.

if isvector(v)
  %true case
  vplus = max(v); % returns a scalar
  vplus(vplus>= vmax) = vmax;
else
  %false case (matrix)
  error('something wrong - v dimension');
end

the dimension get mixed up, the compiler telling me to use all function, however I did the following, and it was the fix

v = v(:); 

before passing it to max, and all solved

I got this problem since I have a variable with flexible size as

if a==b
c = 1;
else
c = [1,1]
end

To solve this problem, I have to define c in advance as [0,0].

It seems that in Matlab Coder the flexible size is not supported.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top