How to use if statements with arrays?

I am trying to use an if statement with an array,
x = 1:1:4
if x > 2
y = x + 1
else
y = x - 1
end
I want the resulting array for y to be [ 0, 1, 4, 5], how would i execute specific functions for only certain numbers in an array? i want y = x + 1 to only affect the numbers in the x array that are greater then 2 and y = x - 1 to only affect the numbers in the x array that are less then 2.

 Respuesta aceptada

Brian B
Brian B el 12 de Feb. de 2013

4 votos

y = (x>2).*(x+1) + (x<=2).*(x-1)

2 comentarios

Dylan Zeigler
Dylan Zeigler el 12 de Feb. de 2013
you are a lifesaver
Brian B
Brian B el 12 de Feb. de 2013
Editada: Brian B el 12 de Feb. de 2013
Just watch out if you want to generalize this. The following will not work (i.e., give you a finite numerical result), for example:
a = [0 1 2];
b = [4 3 2];
y = (a~=0).*(b./a); % ... + (a==0)*0 not needed

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Entering Commands en Centro de ayuda y File Exchange.

Preguntada:

el 12 de Feb. de 2013

Editada:

el 28 de En. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by