A query relating a function with 3 input arguments.

My code is:
function i = Three_inputsFunction (x,y,z)
if x>y>z || y>x>z
x+y
elseif x<y<z || x<z<y
y+z
else
x+z
end
end
>> Three_inputsFunction (-18,-3,-6)
ans =
-21
Query : Why is the answer '-21' and not '-9'?

 채택된 답변

Stephen23
Stephen23 2021년 8월 12일
편집: Stephen23 2021년 8월 12일
"Why is the answer '-21' and not '-9'?"
Because this code
x>y>z
(x>y)>z
which (because true==1 and false==0) is equivalent to either of these
1>z
0>z
You need this instead:
x>y && y>z
Also note that you do not define the function output i.

댓글 수: 6

Fixed it for you too:
Three_inputsFunction (-18,-3,-6)
ans = -9
function Three_inputsFunction(x,y,z)
if x>y && y>z || y>x && x>z
x+y
elseif x<y && y<z || x<z && z<y
y+z
else
x+z
end
end
i see, understood.
but confused with your 2nd elaboration :
1>z
0>z
Would you mind detailing me please. I am new to Matlab.
Thanks for your quick reply though. :)
Stephen23
Stephen23 2021년 8월 12일
편집: Stephen23 2021년 8월 12일
"Would you mind detailing me please."
This comparison
x>y
can return either
true
or
false
so your code (I added the parentheses for clarity, but these do not change the order of operations):
(x>y)>z
will give either of these two situations:
(true)>z
(false)>z
or using the equivalent numeric values (in MATLAB true==1 and false==0):
(1)>z
(0)>z
from which we can trivially remove the parentheses:
1>z
0>z
So you thought you were performing a comparison of three variables, but in reality you were actually just comparing z against zero or one. The rules of precedence explain why.
Alright, many thanks!
@Alek Poudel: you can also show your thanks by accepting my answer :)
ohh yeah, done! didn't know about that before. Cheers!

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

추가 답변 (0개)

카테고리

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

질문:

2021년 8월 12일

댓글:

2021년 8월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by