Maximum value in a vector

11 ビュー (過去 30 日間)
NT
NT 2016 年 3 月 23 日
コメント済み: sunil shetty 2019 年 5 月 17 日
Problem statement: Use the max function to find the value and location of the maximum y value. Use fprintf to show the maximum y and the x value for which it occurs. When I use the max function it always returns -1?
x = [linspace(-pi,pi,10)]
n = [length(x)];
for i = 1:n
fprintf(' %.0f: %f ', i, x(i))
end
for i = 1:n
y = [cos(x(i))];
fprintf(' %f ',y)
end
max(y)

採用された回答

Stephen23
Stephen23 2016 年 3 月 23 日
編集済み: Stephen23 2016 年 3 月 23 日
The problem is that you don't have a vector, although you think that you do. Actually y is a scalar value -1, so of course min(-1) will give you that output. This happens because you simply reallocate y on every loop iteration, so at the end of the loop it only has the last value. You could use indexing to fix this.
A much better way to solve this problem is entirely without loops:
>> X = linspace(-pi,pi,10);
>> Y = cos(X);
>> [maxY,idx] = max(Y);
>> maxX = X(idx)
maxX = -0.34907
>> maxY
maxY = 0.93969
Loops are often an inefficient way of solving problems in MATLAB.
  3 件のコメント
Stephen23
Stephen23 2016 年 3 月 23 日
Like I said: use indexing to store the y values in the loop. Then apply max after the loop. Indexing is covered in thousand of tutorials online, so you won't have any problem with that.
sunil shetty
sunil shetty 2019 年 5 月 17 日
Hi ,
Is this solution applicable for 2D or 3D vector ?
Thanks & Regards ,
Sunil

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by