MATLAB: Logical indexing: More than two conditions

if-else statement fastlogical indexing

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

Best Answer

Do you mean
x = -10:10;
y = (x>=0 & x~=2).*x.^3 + (x<0).*x.^2 + (x==2).*x