フィルターのクリア

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

3 ビュー (過去 30 日間)
Sámuel Varga
Sámuel Varga 2018 年 10 月 25 日
回答済み: Steven Lord 2018 年 10 月 25 日
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

回答 (1 件)

Steven Lord
Steven Lord 2018 年 10 月 25 日
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.

カテゴリ

Help Center および File ExchangeMATLAB Compiler についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by