필터 지우기
필터 지우기

write a three_max function

조회 수: 23 (최근 30일)
Britnie Casillas
Britnie Casillas 2019년 10월 16일
댓글: Thanishq 2023년 10월 26일
* 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
Thanishq
Thanishq 2023년 10월 26일
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

댓글을 달려면 로그인하십시오.

채택된 답변

Daniel M
Daniel M 2019년 10월 17일
There are several issues with your code.
  1. It does not return an output.
  2. It overloads the max() function, which can lead to confusing issues.
  3. 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
Daniel M
Daniel M 2019년 10월 17일
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)
Britnie Casillas
Britnie Casillas 2019년 10월 17일
I believe it works now!
When I type three_max(1,10,5) in the command window, it returns with the highest value, in this case 10. I think is what my professor is looking for!
Thank you!!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by