find max number in matlab
Sebastian Wright
this is my code in matlab
n1=input('Please enter a number:');
n2=input('Please enter a number:');
n3=input('Please enter a number:');
n4=input('Please enter a number:');
n5=input('Please enter a number:');
function max = mymax(n1,n2,n3,n4,n5)
max=n1
if n2>max max=n2;
end
if n3>max max=n3;
end
if n4>max max=n4;
end
if n5>max max=n5;
end
mymax(n1,n2,n3,n4,n5)
fprintf('The maximum number is:%d\n ',max)
endi create the function to find the maximum number between five numbers but i can not print the max number when i run the code i enter five numbers but then my program ends and it does not show me the out put in fact i do not know how should i show the max number
32 Answers
An easier way to do this is just using the built-in max function.
You can make a new matrix with your inputs by:
mat = [n1, n2, n3, n4, n5]Then, to get the max of that matrix just use:
nmax = max(mat)Finally, to get the max value to print, use:
fprintf('The maximum number is: %d\n', nmax) your code ends at line 5 without executing the function after it. Furthermore, your code has a bug that is doing infinite recursive. So you have to remove the call
mymax
in the function.
your code should be fixed like this one:
n1=input('Please enter a number:');
n2=input('Please enter a number:');
n3=input('Please enter a number:');
n4=input('Please enter a number:');
n5=input('Please enter a number:');
mymax(n1,n2,n3,n4,n5)
function max = mymax(n1,n2,n3,n4,n5)
max=n1;
if n2>max max=n2;
end
if n3>max max=n3;
end
if n4>max max=n4;
end
if n5>max max=n5;
end
fprintf('The maximum number is:%d\n ',max)
end