How do I easily avoid out of bounds error in an 'or' expression?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Steven Lord
am 25 Okt. 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 Kommentare
Siehe auch
Kategorien
Mehr zu MATLAB Compiler finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!