if elseif else statement not working

37 次查看(过去 30 天)
Hello, I have just gotten back into matlab and I am practicing the else if statememts. this is currently what I am running:
function [L,w,o] = SortLargestNumber(input,input1,input2)
x = input;
c = input1;
m = input2
x
c
m
HighestNumber = 0;
if x>c && m
HighestNumber = x;
elseif c>x && m
HighestNumber = c;
else m>x && c
HighestNumber = m;
end
HighestNumber
end
I am not sure what I am doing wrong with the else if statement as I am only trying to sort which number is highest. can someone point out why and perhaps provide a better example of doing this? I know the variables are bad, its practice.
Thanks!
-Kie

回答(2 个)

Dave B
Dave B 2021-9-29
编辑:Dave B 2021-9-29
You're writing "x is greater than c and m" and probably thinking of this as "x is greater than c, and x is greater than m". But MATLAB doesn't think of it this way, it sees "x is greater than c...and, unrelated, m" (it interprets that as m>0):
SortLargestNumber(10, 9, 8)
m = 8
x = 10
c = 9
m = 8
HighestNumber = 10
SortLargestNumber(1, 9, 8)
m = 8
x = 1
c = 9
m = 8
HighestNumber = 9
SortLargestNumber(1, 9, 80)
m = 80
x = 1
c = 9
m = 80
ans = logical
1
HighestNumber = 80
function [L,w,o] = SortLargestNumber(input,input1,input2)
x = input;
c = input1;
m = input2
x
c
m
HighestNumber = 0;
if x>c && x>m
HighestNumber = x;
elseif c>x && c>m
HighestNumber = c;
elseif m>x && m>c
HighestNumber = m;
end
HighestNumber
end
  2 个评论
Kieran Smith
Kieran Smith 2021-9-29
Ohhhhhh, was the problem solely needing to edit the if statements to be "x>c && xm" etc? That's a good point if so, that did not cross my mind for some reason.
Dave B
Dave B 2021-9-29
Yes, think of each thing between && and || as being totally independent. Also if your goal is to find the largest number, I fully agree with - just use max, but if your goal is to learn how to write a function that finds the largest number, some more feedback:
  • what about the cases where there are ties?
  • how would you extend this to 4 arguments?...the code will have to grow quite a bit with each additional value
  • Consider setting the initial value of HighestNumber to NaN, it might make it easier to notice an error.
  • What are the outputs of this function supposed to be?

请先登录,再进行评论。


David Hill
David Hill 2021-9-29
If-Else Method:
function largestNumber = SortLargestNumber(x,c,m)
if x>=c && x>=m
largestNumber = x;
elseif c>x && c>=m
largestNumber = c;
else
largestNumber = m;
end
Better method with built-in function:
largestNumber = max([x,c,m])

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by