Search code examples
matlabmatrixmultidimensional-arrayindexingminimum

(Matlab) Dimensional indexing using indices returned by min function


Suppose I have a 5-d matrix C. I use the following code to get a min matrix C3 (each element of C3 represents the minimum of dimension 1,2,3):

[C1, I1] = min(C,[],1);
[C2, I2] = min(C1, [], 2);
[C3, I3] = min(C2, [], 3);

The question is how to get the index of the minimum in terms of each dimension? For example consider this simpler case:

C = [1,2;3,4]

The minimum here is 1, its index in dimension 1 is 1 (first row) and in dimension 2 also 1 (first column).

I know that changing the sequence of these expressions would give me the right answer, but what if I want to get all dimensional indices with computing these expressions only once?


Solution

  • Use this for a 5D matrix -

    [~,ind] = min(C(:))
    [ind_dim1,ind_dim2,ind_dim3,ind_dim4,ind_dim5] = ind2sub(size(C),ind)
    

    Edit 1: This is for a case where you are not exactly looking for global but dimension specific minimum values and indices.

    Code

    %%// Random data for demo
    C = randi(60,2,3,4,2,3);
    
    %%// Your method
    [C1, I1] = min(C,[],1)
    [C2, I2] = min(C1, [], 2)
    [C3, I3] = min(C2, [], 3)
    
    %%// My method
    dimID = 3; %%// Dimension till when minimum is to be found out
    C_size = size(C);
    dim_v1 = prod(C_size(1:dimID))
    dim_v2 = prod(C_size(1:dimID-1))
    
    t1 = reshape(C,[dim_v1 C_size(dimID+1:end)])
    [val,ind1] = min(t1,[],1)
    chk1_ind = ceil(ind1/dim_v2)
    
    %%// This might suffice for you, but you insist to get the indices in the format 
    %%// identical to the one obtained from your method, try the next steps
    
    C_size(1:dimID)=1;
    chk2_ind = reshape(chk1_ind,C_size)
    
    %%// Verify
    error_check = isequal(chk2_ind,I3)