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

标签 matlab

我有以下代码:

[~,ind]=max(Defender.Q,[],6);

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

Defender.Q的第6维有多个最大值时,max函数 正在给我这些多个最大值中第一个的索引。我想得到一个索引 在多个最大值之间随机化。有任何想法吗?感谢您的帮助!

最佳答案

好吧,这有点复杂,但你可以获得所有最大值的索引,然后使用 randiaccumarray 随机选择一个:

%# (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);

关于MATLAB:当有多个最大值时,如何不获取第一个元素而是从 "max"获取随机索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10543716/

相关文章:

matlab - 使用 Octave\MatLab 进行 ML 梯度下降成本函数的简单演算到底是如何工作的?

c++ - Matlab 无法正确初始化 C++ 共享库

matlab - 是否可以将嵌套包导入 matlab 函数

matlab - 如何从我的数据中为 surf() 创建一个二维矩阵?

MATLAB:嵌套 for 循环每次连续迭代都需要更长的时间

excel - 将 Excel 数字复制到剪贴板时的小数精度

MATLAB 的 hmmtrain 假定初始状态为 1

java - 保持 MATLAB 的 "pwd"和内部 "user.dir"同步

c++ - 使用 C++ 编译器设置 MATLAB

matlab - Octave 音程中的行明智操作