Filter löschen
Filter löschen

Logical indexing: More than two conditions

58 Ansichten (letzte 30 Tage)
balandong
balandong am 2 Dez. 2016
Kommentiert: balandong am 2 Dez. 2016
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

Akzeptierte Antwort

Mischa Kim
Mischa Kim am 2 Dez. 2016
Do you mean
x = -10:10;
y = (x>=0 & x~=2).*x.^3 + (x<0).*x.^2 + (x==2).*x
  1 Kommentar
balandong
balandong am 2 Dez. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by