How to calculate a max value in a array without the built in functions.

468 views (last 30 days)
The array is
Time = [1,6,3,6,8,12,1]
I think you need to use a for or while loop. There is no predetermined max value however as it is time.
Thanks.

Accepted Answer

Mischa Kim
Mischa Kim on 12 Mar 2014
Edited: Mischa Kim on 12 Mar 2014
Giuseppe, a for-loop would be the way to go:
maxval = Time(1);
for ii = 1:length(Time)
if Time(ii) > maxval
maxval = Time(ii);
end
end
Alternatively, you could use max(Time).
  4 Comments
manikanth Jonnadula
manikanth Jonnadula on 29 Apr 2022
Hey mate, can you help me how to find the Max Array from 5 identical Datasets using double For Loops please.

Sign in to comment.

More Answers (2)

Carlos
Carlos on 12 Mar 2014
Edited: Carlos on 12 Mar 2014
A very easy newbie way to do it using a while loop (better with a for loop as Mischa states)
>> Time = [1,6,3,6,8,12,1];
>> max=Time(1);k=1;
>> while(k<=length(Time))
if(Time(k)>max)
max=Time(k);
end
k=k+1;
end
  3 Comments
Giuseppe
Giuseppe on 14 Mar 2014
thank you this is still useful. now i understand more about while vs for loops.

Sign in to comment.


Shivani Dixit
Shivani Dixit on 1 Jun 2021
You can use for loop or while loop for finding out the maximum or minimum element in the array without using any built-in functions.
Finding out maximum value in an array using for loop is shown below:
Time = [1,6,3,6,8,12,1];
ans = Time(1); % Initially take maximum element as first element and after iterating over the loop we will get final answer
for i=1:length(Time)
if(Time(i)>ans)
ans=Time(i);
end
end
% The variable 'ans' would store the final maximum value

Community Treasure Hunt

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

Start Hunting!