Finding the maximum value without using built-in functions
Mostrar comentarios más antiguos
My instructor assigned me a problem to solve, but unfortunately I couldn't, though I know it's an easy trick. I will write the program first, then I will ask the question:
n=input('Enter the number of the student: ');
for a=1:n
B(a)=input('Enter the grades as numerical values: ');
end
It's clear that variable B is a matrix containing the grades as numerical values. The problem that's assigned to me, is to find a way to show the biggest grade in the matrix without using MAX function or any other built-in functions, but rather by comparing the grades using for loop. It's like comparing the first grade with the other grades, and then the loop will keep assigning the bigger value each time the condition is verified.
I don't know how to do it although I have tried numerous times, so I would be thankful for your help.
Respuesta aceptada
Más respuestas (3)
Andy
el 13 de Mayo de 2011
0 votos
Before the loop, create a variable called currMax, and set it equal to 0. Within the loop, with each grade that's entered, compare it to currMax. If it is bigger than currMax, then you can replace currMax with that new grade. Otherwise, do not replace currMax. There's not much more to say without doing your assignment for you.
3 comentarios
Matt Tearle
el 13 de Mayo de 2011
Slight improvement (IMHO): set currMax to the first element, then loop over the rest. (In this case we can assume all the values are positive, but not in general.)
Andy
el 13 de Mayo de 2011
Fair enough, but if the class is receiving negative grades, then there are bigger problems than our mistaken assumption. :)
Sean de Wolski
el 13 de Mayo de 2011
Initialize currMax to -inf, for Andy's method.
Sean de Wolski
el 13 de Mayo de 2011
Those professors are wising up to the:
the_max = min(-x);
%or
s = sort(x);
the_max = s(end);
tricks...
1 comentario
Matt Tearle
el 13 de Mayo de 2011
Fight back! This assignment, as stated ("any other built-in function"), is impossible! Proof:
which gt
edit gt
Abdullah
el 13 de Mayo de 2011
0 votos
1 comentario
Sean de Wolski
el 13 de Mayo de 2011
just record a inside the if statement.
if B(a) > maxgrade
maxgrade=B(a);
idx = a;
end
Categorías
Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!