if all elemets of a array equal, which array will be choose by MAX function?

1 回表示 (過去 30 日間)
Ararat Cetinkaya
Ararat Cetinkaya 2020 年 5 月 17 日
編集済み: Stephen23 2020 年 5 月 18 日
Hi
I have an a = [0, 0 , 0 , 0 , 0 ] matrix and when try to use max(a) it always choose the first element as a max value. I need a function like MAX(x) but when all the elements are equal to each other is should choose the one of them randomly. is there any function like that ?

採用された回答

Stephen23
Stephen23 2020 年 5 月 17 日
編集済み: Stephen23 2020 年 5 月 18 日
There is no inbuilt function, but you can do it yourself very easily:
>> a = [0,0,0,0,0];
>> ida = find(a==max(a));
>> idx = randi(numel(ida))
idx = 4
>> a(ida(idx))
ans = 0
  2 件のコメント
Steven Lord
Steven Lord 2020 年 5 月 17 日
Don't use idx as an index into a. Use it as an index into ida.
a = [1:100 0 0];
ida = find(a == min(a))
idx = randi(numel(ida))
fprintf("Element %d of a is %d.\n", idx, a(idx));
fprintf("Element %d of the vector %s is %d, corresponding to %d in a.\n", ...
idx, mat2str(ida), ida(idx), a(ida(idx)))
The same idea holds when using max instead of min.
Stephen23
Stephen23 2020 年 5 月 17 日
@Steven Lord: thank you for bringing that to my attention... that was actually my original intent, but got lost somewhere along the way. Fixed now.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGraphics Object Programming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by