arraysmatlabsortingindexingn-dimensional

Sort and keep index of a n-dimension array -- MATLAB


I have a 12-D array and am using each dimension as an index value in an optimization problem.

A(:,:,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10)

each index value i is a value from 1 to 5.

I want to sort A from greatest to least and keep track of the indices so I know which indices correspond to to what value of A.

So my ideal output would be a 2 column cell/array with one column being the value and the other other column being the index values.

For a simple 3D example: say I have a 3D array: A(:,:,i1).

Where:

A(:,:,1) =  2 
A(:,:,2) =  6 
A(:,:,3) =  13 
A(:,:,4) =  11 
A(:,:,5) =  5  

I would like my output to be:

13   3
11   4
6    2
5    5
2    1

EDIT:

assume I have 1x1x3x3 sized input such that

A(1,1,1,1) = 3

A(1,1,2,1) = 1

A(1,1,3,1) = 23

A(1,1,1,2) = 12

A(1,1,2,2) = 9

A(1,1,3,2) = 8

A(1,1,1,3) = 33

A(1,1,2,3) = 14

A(1,1,3,3) = 6

the expected output would be:

33  [1,1,1,3]

23  [1,1,3,1]

14  [1,1,2,3]

12  [1,1,1,2]

9  [1,1,2,2]

8  [1,1,3,2]

6 [1,1,3,3]

3  [1,1,1,1]

1  [1,1,2,1]


Solution

  • This should be a generic code for any multi-dimensional input array -

    %// Sort A and get the indices
    [sorted_vals,sorted_idx] = sort(A(:),'descend'); 
    
    %// Set storage for indices as a cell array and then store sorted indices into it
    c = cell([1 numel(size(A))]); 
    [c{:}] = ind2sub(size(A),sorted_idx);
    
    %// Convert c to the requested format and concatenate with cell arary version of 
    %// sorted values for the desired output
    out = [num2cell(sorted_vals) mat2cell([c{:}],ones(1,numel(A)),numel(size(A)))]; 
    

    The generic code owes its gratitude to this fine solution.