MATLAB: How to NOT get the first element, but a random index from "max" when there are multiple highs?

I have the following code:

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

Defender.Q - HUGE multidimensional matrix.

When there are several highs in the 6th dimension of Defender.Q , the max function gives me the index of the first of these multiple highs. I want to get an index that is randomized between several highs. Any ideas? Thanks for your help!

+4
source share
1 answer

Ok, this is a bit related, but you can get the indices of all the highs, and then randomly select one using randi and 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); 
+5
source

Source: https://habr.com/ru/post/1411894/


All Articles