How do I easily avoid out of bounds error in an 'or' expression?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
This is in the doc of the if:
x = 42;
if exist('myfunction.m','file') && (myfunction(x) >= pi)
disp('Expressions are true')
end
The first part of the expression evaluates to false. Therefore, MATLAB does not need to evaluate the second part of the expression, which would result in an undefined function error.
However, this doesn't seem to work with or. Do I have to write two ifs or is there a simplier way to program it?
This is my code:
if (length(minx)==1)||(minx(2)>30);
%do something.
end
0 comentarios
Respuestas (1)
Steven Lord
el 25 de Oct. de 2018
If the first condition of an and expression is false, we don't have to evaluate the second condition. false and anything is false.
If the first condition of an and expression is true, we do need to evaluate the second condition. In that case, the result of the and will be equal to the result of the second condition. [1]
If the first condition of an or expression is true, we don't have to evaluate the second condition. true or anything is true.
If the first condition of an or expression is false, we do need to evaluate the second condition. In that case, the result of the or will be equal to the result of the second condition. [1]
Your if condition will be satisfied if either minx is a scalar or its second element is greater than 30. It will error if minx is empty. In that case length(minx) is 0 which makes the first condition false. Since minx is empty it doesn't have a second element. What you want to happen in the "minx is empty" case will determine what you need to add or modify in your code.
[1] I'm ignoring NaN here.
0 comentarios
Ver también
Categorías
Más información sobre MATLAB Compiler en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!