Having two logical operators in one for statement

6 ビュー (過去 30 日間)
Antonio Herrera
Antonio Herrera 2024 年 10 月 21 日 19:22
コメント済み: Walter Roberson 2024 年 10 月 21 日 20:14
I am trying to check if three logical statements are true in order to proceed with the for statement, otherwise the function would return 0. Does this work and if not how should I proceed?
if abs(p(i)) > sigma_d && -p(i) <= 0 && d(i) > 0
ddot = -A1*(abs(p(i))/sigma_d - 1);
else
ddot = 0;
end
  1 件のコメント
Walter Roberson
Walter Roberson 2024 年 10 月 21 日 19:43
&& -p(i) <= 0
as a matter of form, I recommend the test
&& p(i) >= 0
The negative logic is unnecessarily confusing.

サインインしてコメントする。

採用された回答

Taylor
Taylor 2024 年 10 月 21 日 19:27
It works, but you will need to consider the precedence of the various logical operators https://www.mathworks.com/help/matlab/matlab_prog/operator-precedence.html
  3 件のコメント
Steven Lord
Steven Lord 2024 年 10 月 21 日 20:11
If the first condition is false, the second and third will not be executed. false and-ed with anything is false so we know the whole expression is false.
If the first condition is true but the second condition is false, the third will not be executed for the same reason as above. true and false is false and false and-ed with anything is false.
Walter Roberson
Walter Roberson 2024 年 10 月 21 日 20:14
The && operator stops executing as soon as the left side is false. With the && operator, the right side is not executed at all if the left side is false. So you can have code such as
A = 0;
A ~= 0 && error("A non-zero")
ans = logical
0
Notice the error was not triggered: it stopped executing as soon as the left side was false

サインインしてコメントする。

その他の回答 (0 件)

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by