findMax function returning the last value of an xlsread array

2 vues (au cours des 30 derniers jours)
Lillian Lau
Lillian Lau le 26 Juil 2018
Hello, I wrote a findMax function to find the maximum value of all the values stored in an array. I am reading an xlsx file into the array and then using findMax function on it. However, it keeps returning the last value of the array. Here's my code:
function max = findMax(input_array)
L = length(input_array);
for i = 1:L-1
temp = input_array(i);
nextVal = input_array(i+1);
if temp >= nextVal
max = temp;
else
max = nextVal;
end
end
end
Where am I going wrong? Would appreciate some help, and thanks in advance!
  1 commentaire
madhan ravi
madhan ravi le 26 Juil 2018
Check the max documentation there is already an inbuilt function in matlab as max.

Connectez-vous pour commenter.

Réponses (1)

Walter Roberson
Walter Roberson le 26 Juil 2018
When i becomes L-1, you will set max to either input_array(L-1) or to input_array(L), ignoring everything else you know about max to that point.
You should be initializing max to -inf, and comparing the elements one by one, and if they are greater than the previous max then make the value the new max. You never need to look at the adjacent value when you use this strategy.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by