How to calculate a max value in a array without the built in functions.
古いコメントを表示
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.
採用された回答
その他の回答 (2 件)
Shivani Dixit
2021 年 6 月 1 日
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
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 件のコメント
Sean de Wolski
2014 年 3 月 12 日
Why is a while-loop better than a for-loop? You use a while loop when you don't know how many times it's going to have to run. Here you do, 1:numel(Time)
Carlos
2014 年 3 月 12 日
I think you misunderstood what I have stated. I have pointed out it is a better practice to do this with a for loop(please read my answer again), but Giuseppe mentioned the possibility of implementing it with a while loop and that is the reason I posted the code with a while loop.
Giuseppe
2014 年 3 月 14 日
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!