write a three_max function
11 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Britnie Casillas
am 16 Okt. 2019
Kommentiert: Thanishq
am 26 Okt. 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 Kommentar
Thanishq
am 26 Okt. 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
Akzeptierte Antwort
Daniel M
am 17 Okt. 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 Kommentare
Daniel M
am 17 Okt. 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)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!