Only the first if-statement block executes,

5 Ansichten (letzte 30 Tage)
Noob
Noob am 3 Okt. 2024
Kommentiert: Walter Roberson am 19 Okt. 2024
Hi there!
I wrote an if-statement, followed by an if-else statement, followed by another if-else statement, followed by the end keyword.
The goal is to use different formulas for different values of alpha, something like the below.
However, it seems that only the first if-statement block executes -- for all possible values of alpha, even when alpha already exceeds that interval.
Where is my mistake? Thanks in advance.
alpha = linspace(0,3*pi/2,1000)
if 0 <= alpha <= pi/2
vx = ...;
vy = ...;
elseif pi/2 < alpha <= pi
vx = ...;
vy = ...;
elseif pi < alpha <= 3*pi/2
vx = ...;
vy = ...;
end

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 3 Okt. 2024
Bearbeitet: Walter Roberson am 3 Okt. 2024
if 0 <= alpha <= pi/2
MATLAB interprets that as
if ((0 <= alpha) <= pi/2)
the first part, 0 <= alpha, produces a logical value, 0 or 1.
The second part compares that 0 or 1 to pi/2 and finds that 0 or 1 is always less than pi/2 so the overall test always succeeds.
MATLAB is not defined as chaining operations. In practice, chaining operations like you show is permitted in Symbolic Mathematics contexts, especially involving the piecewise() operator.
It is safest to always write the expanded version,
if 0 <= alpha && alpha <= pi/2
  32 Kommentare
Noob
Noob am 19 Okt. 2024
Bearbeitet: Noob am 19 Okt. 2024
What's an equality test?
Do you think my using 0 <= alpha is problematic, and that I should instead use 0 < alpha & alpha == 0?
Also, yes, I found a glaringly obvious error in my equations!
In my equations, I was dividing a vector by another vector; something like 4i + 5j divided by 8i + 10j is nonsensical.
So, I'll work to fix up this issue now.
Walter Roberson
Walter Roberson am 19 Okt. 2024
Suppose that you had
mask = 0 <= alpha & alpha < pi/2;
%some code here
mask = pi/2 < alpha & alpha < pi;
%some code here
then the code would not account for the case of alpha == pi/2 . You need to be careful at the boundaries of your conditions.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Function Creation finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by