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

조회 수: 411 (최근 30일)
zizo
zizo 2011년 6월 14일
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
Jan
Jan 2011년 6월 14일
Think of the case of x==10, e.g. by "10<=x & x < 40".
Walter Roberson
Walter Roberson 2011년 6월 14일
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

댓글을 달려면 로그인하십시오.

채택된 답변

Paulo Silva
Paulo Silva 2011년 6월 14일
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

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2011년 6월 14일
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
Matt Fig
Matt Fig 2011년 6월 14일
@Paulo, perhaps this is better?
and(0<x,x<10)
Sean de Wolski
Sean de Wolski 2011년 6월 14일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by