write a three_max function
50 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Britnie Casillas
il 16 Ott 2019
Commentato: Thanishq
il 26 Ott 2023
* not a homework question. This is a practice question for an upcoming exam
Write a function, three_max, which takes three numbers, x1, x2, x3 and outputs the largest number. Do this without using the variety of built-in functions associated with max and sort. Test it.
I have created a function but when ever I try to test it I get a "not enough input arguments" for line 2: if (x1>x2 && x1>x3). I do not know what I am doing wrong
function three_max(x1,x2,x3)
if (x1>x2 && x1>x3)
max=x1;
elseif (x2>x1 && x2>x3)
max=x2;
elseif (x3>x1 && x3>x1)
max=x3;
end
end
1 Commento
Thanishq
il 26 Ott 2023
hii
this is the program i did :
function [p] = three_max(a,b,c)
if a>b && a>c
p=a;
elseif b>a && b>c
p=b;
else
p=c;
end
As u have this problem:"I have created a function but when ever I try to test it I get a "not enough input arguments" for line 2: if (x1>x2 && x1>x3). I do not know what I am doing wrong "
after writing the code we just simply click run button but in command prompt we have to write this....
>> three_max(1,2,3)
ans =
3
Risposta accettata
Daniel M
il 17 Ott 2019
There are several issues with your code.
- It does not return an output.
- It overloads the max() function, which can lead to confusing issues.
- Your third conditional (which isn't necessary at all) compares against x1 twice.
Finally, I do not get the stated error when I run this code. It must be how you are calling it. Perhaps you have done:
three_max(x1,x2)
The function requires three inputs.
3 Commenti
Daniel M
il 17 Ott 2019
Oh I see. Yes, you need to return an output.
You avoid overloading by not naming variables after built-in functions. I know you are avoiding using the max function in this case, but it's still bad practice. Say, for example, in your function you wanted to compare your answer to the value returned from max, how would you call that function? You can't because you have set max = x1 (or x2, or x3). This should work now.
function x = three_max(x1,x2,x3)
if (x1>x2 && x1>x3)
x = x1;
elseif (x2>x1 && x2>x3)
x = x2;
elseif (x3>x1 && x3>x2)
x = x3;
end
end
Call the function with
maxVal = three_max(x1,x2,x3)
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Time Series Events in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!