MATLAB:当有多个最大值时,如何从"max"获取第一个元素而不是随机索引?

use*_*340 4 matlab

我有以下代码:

[~,ind]=max(Defender.Q,[],6);
Run Code Online (Sandbox Code Playgroud)

Defender.Q 是一个巨大的多维矩阵.

当第6维中有多个最大值时Defender.Q,该max函数给出了这些多个最大值中的第一个的索引.我想获得一个在多个最大值之间随机化的索引.有任何想法吗?谢谢你的帮助!

Jon*_*nas 5

好吧,这有点涉及,但你可以获得所有最大值的索引,然后使用randi和随机选择一个accumarray:

%# (1) Find the maxima

%# if you are interested in the global maximum
%# that may occur multiple times along dimension 6
[maxVal,maxIdx] = max(Defender.Q(:));

%# ALTERNATIVELY

%# if you are interested in local maxima along dimension 6
maxVal = max(Defender.Q,[],6);
maxIdx = find(bsxfun(@eq,Defender.Q,maxVal));

%# (2) pick random maximum for each 5D subarray

%# this assumes that there is no dimension #7 etc
%# In case there is, you need to add a column of ones
%# and then d7 etc to second input of accumarray

%# find row, col, etc subscripts of the maxima
[d1,d2,d3,d4,d5,d6] = ind2sub(size(Defender.Q),maxIdx);

%# create a 5-d array, containing one random index
%# from the maxima along dimension 6, or NaN
randIdx = accumarray([d1,d2,d3,d4,d5],d6,[],@(x)x(randi(length(x))),NaN);
Run Code Online (Sandbox Code Playgroud)

  • 双检查了我的答案,它有缺陷.我正在删除downvote(不幸的是,除非编辑此答案,否则我无法取消选中). (2认同)