findMax function returning the last value of an xlsread array

3 次查看(过去 30 天)
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 个)

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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by