If Statement not using conditionals

19 visualizaciones (últimos 30 días)
Anthony Koning el 13 de Dic. de 2021
Respondida: Steven Lord el 13 de Dic. de 2021
Hi, I wanted to know if anyone knew why my if/else statement was not producing the specified outputs with my current code:
v= (0:5:50)
if 49.9<v<51.1
a_n = .01
else
a_n=(-0.01.*(v-50))./((exp(-(v-50)./10))-1)
end
b_n= exp((v+60)./80)./8
the output of a_n should only be .01 at v=50, yet .01 is the only output and is completely ignoring the else aspect of the statement. Does anyone know why this is, and if so, could you tell me why this is occuring?
0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Steven Lord el 13 de Dic. de 2021
From the documentation "if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false." So the body of your if statement would only execute if all the elements of 49.9<v<51.5 were true.
But there's another issue here. Your condition does not mean what you think it means.
49.9 < v < 51.1 is equivalent to (49.9 < v) < 51.1. The expression inside the parentheses is a logical vector containing only false (equivalent of 0) and true (equivalent of 1) values. Because both 0 and 1 are less than 51.1 your condition is always satisfied.
To detect which elements of v are in the range (49.9, 51.1) use two logical operations combined with an and (the & operator.)
v= (0:5:50)
v = 1×11
0 5 10 15 20 25 30 35 40 45 50
mask = (49.9 < v) & (v < 51.1) % All elements are false except the last which is true
0 0 0 0 0 0 0 0 0 0 1
q = 50
You can use this mask to index and retrieve elements from v, like I did to assign the 50 from it to the variable q, or you can use it to assign to a vector. These are examples of logical indexing
z = zeros(size(v));
z = 1×11
99 99 99 99 99 99 99 99 99 99 42
0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by