Borrar filtros
Borrar filtros

Logical indexing: More than two conditions

58 visualizaciones (últimos 30 días)
balandong
balandong el 2 de Dic. de 2016
Comentada: balandong el 2 de Dic. de 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

Respuesta aceptada

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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by