How to reorder columns of an array of cells based on the order of a vector matrix while storing the rows in Matlab?

I have a 108x8 matrix (called a matrix) that looks like this:

5   8   3   6   2   1   7   4
8   4   2   7   1   3   6   5
5   4   3   2   1   7   8   6
1   7   8   5   6   4   3   2

I have another 108x8 cell array (called data) that looks like this:

   'B'  'B' 'B' 'A' 'B' 'B' 'A' 'B'
   'A'  'B' 'B' 'A' 'B' 'A' 'A' 'A'
   'A'  'A' 'B' 'A' 'A' 'B' 'B' 'B'
   'A'  'A' 'A' 'B' 'A' 'A' 'A' 'A'

I want to rebuild the matrix so that each row remains intact and is sorted in ascending order. This can be done using the command [vals order] = sort(matrix,2). I want to rearrange the data matrix in the same way.

Previous solutions suggested using a command, for example:

reordered_data=data(order)

However, this does not give the desired result; it reorders the data, but not in the correct order.

Hope this is clear, please let me know if clarification is required.

Thank.

+5
source share
2

order , .

[vals, order] = sort(matrix,2);
[r,c] = size(matrix);
index = bsxfun( @plus, order, (0:r-1)'*c );
data = data';
reordered_data = data(index')';
+1

sortrows?

[vals, I] = sortrows(matrix);
for i = 1:size(matrix,1);
     reordered_data(i,:) = data(I(i),:);
end

:

reordered_data = 

    'A'    'A'    'A'    'B'    'A'    'A'    'A'    'A'
    'A'    'A'    'B'    'A'    'A'    'B'    'B'    'B'
    'B'    'B'    'B'    'A'    'B'    'B'    'A'    'B'
    'A'    'B'    'B'    'A'    'B'    'A'    'A'    'A'
0

All Articles