How to reorder cell array columns based on the order of a vector matrix, while keeping rows intact in Matlab?

I have a 108x8 matrix (called 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 rearrange the matrix such that each row remains intact and is sorted in ascending order. This can be easily done with the [vals order] = sort(matrix,2) command. I want to rearrange the data matrix in the same manner.
Previous solutions suggested the use of a command such as:
reordered_data=data(order)
However, this does not give the desired outcome, it does rearrange the data, but not in the correct order.
Hopefully this is clear, please let me know if clarification is needed.
Thank you.

 Akzeptierte Antwort

Cedric
Cedric am 8 Apr. 2013
Bearbeitet: Cedric am 8 Apr. 2013
Would this work?
>> buffer = arrayfun(@(rId) data(rId,order(rId,:)).', 1:size(order,1), ...
'UniformOutput', false) ;
>> reordered_data = [buffer{:}].'
reordered_data =
'B' 'B' 'B' 'B' 'B' 'A' 'A' 'B'
'B' 'B' 'A' 'B' 'A' 'A' 'A' 'A'
'A' 'A' 'B' 'A' 'A' 'B' 'B' 'B'
'A' 'A' 'A' 'A' 'B' 'A' 'A' 'A'

Weitere Antworten (1)

m = [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];
data = {'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'};
[~,ii] = sort(m,2);
d1 = data';
out = d1(bsxfun(@plus,ii,(0:size(ii,1)-1)'*size(ii,2))')';

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by