Sort and keep index of a n-dimension array
3 views (last 30 days)
Show older comments
I have a 12-D array and am using each dimension as an index value in an optimization problem.
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.
Harry on 30 Oct 2014
Edited: Harry on 30 Oct 2014
As I understand it, you have 2 dimensions of data. You have not specified how you want to sort them (e.g. "along dimension 1"). If, in fact, these dimensions are not relevant to the sorting (i.e. you want to sort all values into one single list), then you can effectively vectorise this 2D matrix using the reshape() operator.
More importantly, your indexing is very excessive in its use of dimensions. You can easily store all the indexing information in just one dimension by encoding each [i1,i2,...,i10] into a single number. After all, there are only 5^10 (i.e. fewer than 10 million) possible index combinations - so we can easily fit this into one number. Here is an example:
close all; clear all; clc;
% N example index values in [1,M]
N = 10;
M = 5;
indexes = randi(M,N,1);
% Encode indices as a single number
encoder = M.^[0:N-1];
code = encoder*indexes
decoded = zeros(N,1);
for i = 1:N-1
next = ceil(code/encoder(i+1)-1)*encoder(i+1);
decoded(i) = (code - next) / encoder(i);
code = next;
decoded(N) = code/encoder(end);
% Check the code/decode works
This will, at worst, leave you with a 3D array, which should be straightforward to handle.
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!