How to use for loop to get the minimum number in an array

For simplicity, I have
A=[ 11 7 10 9 6 4 3]
and
B=8
I want to have a for loop to compare each of the elements in A with the latest minimum number from the for loop to get the final minimum number in A.
For example, when A(1) compare with B, min=8, then i continue with the A(2) compare with min=8, this time min=7. After that, A(3) compare with min=7, new min=7. The steps continue till the last elements of A.

 採用された回答

Jos (10584)
Jos (10584) 2014 年 6 月 16 日

0 投票

A = [ 11 7 10 9 6 4 3]
B = 8
result = min([A B])
% or if you insist on using a for-loop (why?)
result = B
for k = 1:numel(A)
if A(k) < result,
result = A(k)
end
end

その他の回答 (1 件)

Abhishek M
Abhishek M 2014 年 6 月 16 日
編集済み: Abhishek M 2014 年 6 月 16 日

0 投票

Hi Grace, I guess this is what you are expecting. Please find the demo example below.
a=[1:2:10];
b=4;
for i=1:5
if a(i)<b
min=b;
else
min=a(i);
end
end

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2014 年 6 月 16 日

回答済み:

2014 年 6 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by