Only the first if-statement block executes,

2 visualizaciones (últimos 30 días)
Noob
Noob el 3 de Oct. de 2024
Comentada: Walter Roberson el 19 de Oct. de 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

Respuesta aceptada

Walter Roberson
Walter Roberson el 3 de Oct. de 2024
Editada: Walter Roberson el 3 de Oct. de 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 comentarios
Noob
Noob el 19 de Oct. de 2024
Editada: Noob el 19 de Oct. de 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 el 19 de Oct. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Function Creation en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by