How to access multidimensional arrays in MATLAB with mixed index

Suppose I have two arrays: M1 and M2. Both have dimensions mxnx p. I am interested in the mxn array from M1 corresponding to the maximum element along the third dimension, so I:

[M1max, indices]=max(M1,[],3); 

Both M1max and indices are mx n arrays. But now suppose that I want to access the elements of M2 that correspond to these maximal elements in M1 (that is, I want all the elements of M2 with the same index as the element M1 that ended up in M1max). How to do it?

+4
source share
3 answers

I think this should do it:

 [yx]=ndgrid(1:size(M1,1),1:size(M1,2)); reshape(M2(sub2ind(size(M1),y(:),x(:),indices(:))),[size(M1,1),size(M1,2)]); 

you want the whole index with idx <-> (y,x,indices(y,x)) , this will compute it. And then calculate M2(idx) and change it in the best way.

+2
source

Another way is to ignore indexes from max :

 indices2 = M1 == repmat(M1max,[1,1,size(M1,3)]); result = reshape(M2(indices2),size(M1max)); 

Compared to doubling, there may be a problem with accuracy. In this case, you can do

 indices2 = repmat(M1max,[1,1,size(M1,3)]) - M1 < eps; 

In addition, there will be a problem with this code if in M1 in the 3rd dimension there are several identical maximum values. We can catch this case with

 assert(sum(indices2(:))==numel(M1max),'Multiple maximum values found') 
+1
source

This may be a little faster than the @Oli suggestion, but they are basically equivalent:

 [M1max, indices] = max(M1,[],3); [mnp] = size(M1); idx = (1:m*n).' + (indices(:)-1)*m*n; M2max = reshape(M2(idx), m, n); 
0
source

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


All Articles