How do I make an if, elseif, else statement?

966 visualizaciones (últimos 30 días)
zizo
zizo el 14 de Jun. de 2011
if 0<x<10
y=4*x
elseif 10<x<40
y = 10*x
else
y = 500
end
I would expect test cases of
x= -1
x= 5
x= 30
x=100
  2 comentarios
Jan
Jan el 14 de Jun. de 2011
Think of the case of x==10, e.g. by "10<=x & x < 40".
Walter Roberson
Walter Roberson el 14 de Jun. de 2011
Good point, Jan.
zizo, Jan's point here is one that I pointed out to you before, when you asked a question a month ago, http://www.mathworks.com/matlabcentral/answers/7479-just-q

Iniciar sesión para comentar.

Respuesta aceptada

Paulo Silva
Paulo Silva el 14 de Jun. de 2011
The correct way to do the conditions is this:
if 0<x & x<10
y=4*x
elseif 10<x & x<40
y=10*x
else
y=500
end

Más respuestas (1)

Sean de Wolski
Sean de Wolski el 14 de Jun. de 2011
Or the vectorized solution:
y = repmat(500,size(x));
idx = 0<x&x<10;
y(idx) = 4*x(idx);
idx = 10<x&x<40;
y(idx) = 10*x(idx);
  3 comentarios
Matt Fig
Matt Fig el 14 de Jun. de 2011
@Paulo, perhaps this is better?
and(0<x,x<10)
Sean de Wolski
Sean de Wolski el 14 de Jun. de 2011
Is it just the order of operations that worries you?
BTW. I'm not even sure my approach would be faster than with the accelerated for-loops.

Iniciar sesión para comentar.

Categorías

Más información sobre Introduction to Installation and Licensing en Help Center y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Community Treasure Hunt

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

Start Hunting!

Translated by