if elseif else statement not working

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 Commento

What are L, w, and o? You need to define the. o is a bad name by the way.

Accedi per commentare.

Risposte (2)

Dave B
Dave B il 29 Set 2021
Modificato: Dave B il 29 Set 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)
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 Commenti

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.
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?

Accedi per commentare.

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])

1 Commento

Wow, that is way more efficient! thankyou for the insight!

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Prodotti

Release

R2021b

Richiesto:

il 29 Set 2021

Commentato:

il 29 Set 2021

Community Treasure Hunt

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

Start Hunting!

Translated by