How can I find the smallest element in an array without using the function 'min'??

30 ビュー (過去 30 日間)
aya qassim
aya qassim 2018 年 12 月 25 日
コメント済み: madhan ravi 2018 年 12 月 26 日
for example I need to find the minimum element in array [1 2 4 3 0 -1 8 9 -2] but without using the function min.
I cannot also use sort.
  1 件のコメント
Stephen23
Stephen23 2018 年 12 月 26 日
>> X = [1,2,4,3,0,-1,8,9,-2];
>> V = unique(X);
>> V(1)
ans = -2

サインインしてコメントする。

採用された回答

Andrei Bobrov
Andrei Bobrov 2018 年 12 月 26 日
X = [1 2 4 3 0 -1 8 9 -2];
min1 = X(1);
idx = 1;
for ii = 2:numel(X)
if X(ii) < min1
min1 = X(ii);
idx = ii;
end
end

その他の回答 (1 件)

madhan ravi
madhan ravi 2018 年 12 月 25 日
X = [1,2,4,3,0,-1,-8,9,-2];
for i =1:numel(X)-1
if X(i)>X(i+1)
min=X(i+1);
else
continue
end
end
  2 件のコメント
Image Analyst
Image Analyst 2018 年 12 月 26 日
Not a good idea to use "min" as the name of a variable because it's an important built-in function. And you also forgot to initialize it, so the code will fail if x has all the same values. Andrei's answer is the way to do it.
madhan ravi
madhan ravi 2018 年 12 月 26 日
Yes sir thank you :) , missed that part.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeTime Series Events についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by