Search code examples
matlabmatrixmatrix-indexing

Linear index of the maximum of a multi-dimensional matrix - MATLAB


Let's say I have a 3-dimensional matrix and have computed the max along the second dimension, and want to get the linear indices of the max values. However, the max-function only returns the subscripts along one dimension.

A = randn([5,5,5]);        % Generate random matrix
[M, Ind] = max(A,[],2);    % Take the max along dimension 2

How do I transfer the index to linear indexing, such that

M == A(Ind)

becomes true?

My intention for this problem is that I have two multi-dimensional matrices and need to compute the max in the first one. Then, I want to access the values in the second matrix at exactly those positions where I found a max in the first one.


Solution

  • One way is to use sub2ind:

    A = randn([5,5,5]);       
    [M, col] = max(A,[],2);   
    
    [m,n,o] = size(A);
    
    dim1 = mod((0:m*o-1)', m)+1;
    dim2 = col(:);
    dim3 = ceil((1:m*o)/m)';
    
    ind = sub2ind(size(A), dim1, dim2, dim3)
    

    verify it works with

    isequal(M(:), A(ind))
    

    to get them to have the same shape as M:

    reshape(ind, m, 1, o)