Clear Filters
Clear Filters

Logical indexing: More than two conditions

61 views (last 30 days)
Say,I have a vector of x, and each particular x that according to the rule 1) less than zero, 2) greater than zero, and 3) equal to 2, will satisfy different equation. I know, by using simple IF-Else condition, we can have the framework as below. x = rand(-3,3)
Case 1
if x > 0 y=x^3 elseif x < 0 y=x^2 elseif x = 2 y = x else
However, I am interested to use the logical indexing. I know, for a two conditions, the arrangement such that
Case 2
cond1 = (x > 0) | (x < 0) y = cond1.*(x^3) + ~cond1.*(x^2);
Thus, using the same logic, I tried to modified the above logical indexing to fit the 3 conditions such as
Case 3
cond1 = (x > 0) | (x < 0) | (x == 2) y = cond1.*(x^3) + ~cond1.*(x^2)+ ~cond1.*(2); y = cond1.*(x^3) + ~cond1.*(x^2);
However, I am not able to produce accurate result for the Case 3, any idea how to implement logical-indexing for more than 2 conditions.
Thanks in advance

Accepted Answer

Mischa Kim
Mischa Kim on 2 Dec 2016
Do you mean
x = -10:10;
y = (x>=0 & x~=2).*x.^3 + (x<0).*x.^2 + (x==2).*x
  1 Comment
balandong
balandong on 2 Dec 2016
Hi Mischa, Although different from the syntax such as in Case 2 and Case 3, but your suggested code does the trick. Thanks for the quick response.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!