if elseif else statement not working
42 views (last 30 days)
Show older comments
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
1 Comment
Image Analyst
on 29 Sep 2021
What are L, w, and o? You need to define the. o is a bad name by the way.
Answers (2)
Dave B
on 29 Sep 2021
Edited: Dave B
on 29 Sep 2021
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)
SortLargestNumber(1, 9, 8)
SortLargestNumber(1, 9, 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 Comments
Dave B
on 29 Sep 2021
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
on 29 Sep 2021
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])
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!