If Statement not using conditionals
15 views (last 30 days)
Show older comments
Anthony Koning on 13 Dec 2021
Answered: Steven Lord on 13 Dec 2021
Hi, I wanted to know if anyone knew why my if/else statement was not producing the specified outputs with my current code:
a_n = .01
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 on 13 Dec 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.)
mask = (49.9 < v) & (v < 51.1) % All elements are false except the last which is true
q = v(mask)
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
More Answers (0)
Find more on Unit Conversions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!