If Statement not using conditionals

9 次查看(过去 30 天)
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?

采纳的回答

Steven Lord
Steven Lord 2021-12-13
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
mask = 1×11 logical array
0 0 0 0 0 0 0 0 0 0 1
q = v(mask)
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(~mask) = 99;
z(mask) = 42
z = 1×11
99 99 99 99 99 99 99 99 99 99 42

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by