How to check an array for max and min values

1 回表示 (過去 30 日間)
Alexander West
Alexander West 2019 年 2 月 24 日
コメント済み: Walter Roberson 2019 年 2 月 25 日
function [shallow,deep] = marinaraTrench(arrayz)
min=realmax;
max=0;
for i=1:size(arrayz)
if arrayz(i)>max
max=arrayz(i)
end
if arrayz(i)<min
min=arrayz(i)
end
end
shallow=min
deep=max
end
I'm trying to find the max and minimum values of an array using for loops alone and for some reason it's not always returning the right values
  3 件のコメント
Alexander West
Alexander West 2019 年 2 月 25 日
what does this do?
Walter Roberson
Walter Roberson 2019 年 2 月 25 日
Your code would fail if the maximum value was < 0 because you were initializing the bound on the maximum to 0.

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

採用された回答

Walter Roberson
Walter Roberson 2019 年 2 月 24 日
You should be looping to numel() of the array, not to size() of the array. size() returns a vector of values, so your for loop becomes for i=1:VECTOR . MATLAB defines that as being the same as for i=1:VECTOR(1) which would be for i=1:size(arrayz,1) .
Note: using variables named max and min is going to confuse readers. At if you get into the habit of using those as variable names, you can be 99% sure that at some point, you are going to confuse yourself heavily in some program where you use them as variable names but then expect the functions with those names to work properly.
  1 件のコメント
Alexander West
Alexander West 2019 年 2 月 25 日
oh, okay thanks! i couldn't understand why size/length wouldn't work, but thank you, I get it now!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by