How do I use one IF-END instead of nested IF-ENDs?

How can I rewrite the following statement so that the nested IF-END structure is not needed. And also replace the code with an IF - ELSEIF - END control structure that accomplishes the same outcome.
if x < y
if z < 10
w = x*y*z
end
else
w = (x*y*z).^2
end

 채택된 답변

Matt Fig
Matt Fig 2011년 3월 2일

2 개 추천

I think replacing what you have with an IF-ELSEIF structure would make it less efficient because it would result in more comparisons. Is there a particular reason why you want to do this?
if x < y && z < 10
w = x*y*z;
elseif x>=y
w = (x*y*z).^2;
end
If that is correct, it always makes 3 comparisons, whereas your original sometimes only makes 1 and at most makes 2.

댓글 수: 1

George
George 2011년 3월 2일
no particular reason, just working with code and school work
thank you!

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

추가 답변 (1개)

Paulo Silva
Paulo Silva 2011년 3월 2일

0 개 추천

w=(x*y*z)^(~((x<y) & (z<10))+1)

댓글 수: 2

Matt Fig
Matt Fig 2011년 3월 2일
Pualo, this is not correct. This will always define w, whereas the IF statements above will not. Specifically, look at x=2,y=4,z=15. This could make a difference where w is defined as a default prior to the IF statement, which has a chance to redefine based on specific conditions.
I knew it wasn't perfect, I tried to add that situation but got tired and distracted by something else, maybe you or other person can improve it.

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

카테고리

도움말 센터File Exchange에서 Orange에 대해 자세히 알아보기

제품

질문:

2011년 3월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by