findMax function returning the last value of an xlsread array

2 views (last 30 days)
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!

Answers (1)

Walter Roberson
Walter Roberson on 26 Jul 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.

Community Treasure Hunt

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

Start Hunting!