Borrar filtros
Borrar filtros

write a three_max function

23 visualizaciones (últimos 30 días)
Britnie Casillas
Britnie Casillas el 16 de Oct. de 2019
Comentada: Thanishq el 26 de Oct. de 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 comentario
Thanishq
Thanishq el 26 de Oct. de 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

Iniciar sesión para comentar.

Respuesta aceptada

Daniel M
Daniel M el 17 de Oct. de 2019
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 comentarios
Daniel M
Daniel M el 17 de Oct. de 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)
Britnie Casillas
Britnie Casillas el 17 de Oct. de 2019
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!!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by