Effacer les filtres
Effacer les filtres

How do I easily avoid out of bounds error in an 'or' expression?

3 vues (au cours des 30 derniers jours)
Sámuel Varga
Sámuel Varga le 25 Oct 2018
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

Réponses (1)

Steven Lord
Steven Lord le 25 Oct 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.

Catégories

En savoir plus sur MATLAB Compiler dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by