How can I sort the output matrix according to the prescribed order in a column?
1 view (last 30 days)
Show older comments
Hi all,
I have my output matrix data in nx3 dimension.
Now I wish to sort these data,neither in the ascending nor descending order in a column, but according to the prescribed order in a column.
For example, if my matrix is
1 0.5 0.8
10 0.6 0.5
11 0.3 0.1
13 0.1 0.8
Now I want to sort the matrix according to the prescribed order of "11 10 1 13" in column 1, that is, the sorted matrix is expected to be
11 0.3 0.1
10 0.6 0.5
1 0.5 0.8
13 0.1 0.8
What is your suggestion?
Thanks in advance.
Fei
0 Comments
Answers (2)
dpb
on 6 Jul 2013
Edited: dpb
on 7 Jul 2013
Presuming you have (or can generate) the desired order vector, then it's pretty much trivial--just find where they're located in the original array. This assumes no ties.
Mat
>> ix=[11 10 1 13]';
%
%[erratum -- dpb]
% following returns the locations in the index vector, NOT in the array
>> [~,ib]=ismember(M(:,1),ix); % INCORRECT original posting
%
% It was intended to interchange the order of arguments as follows
>> [~,ib]=ismember(ix,M(:,1)); % CORRECT
%[ end erratum]
>> M(ib,:)
ans =
11.0000 0.3000 0.1000
10.0000 0.6000 0.5000
1.0000 0.5000 0.8000
13.0000 0.1000 0.8000
>>
2 Comments
dpb
on 7 Jul 2013
_This works efficiently, however I think there might be an error in your code.
[~,ib]=ismember(M(:,1),ix)
...the right one is
[~,ib]=ismember(ix,M(:,1)) _
That is correct, sorry--I did inadvertently swap the order of which is in which in the argument list and by chance the original sample case didn't show it up...
Andrei Bobrov
on 7 Jul 2013
Edited: Andrei Bobrov
on 8 Jul 2013
a = [1 0.5 0.8
10 0.6 0.5
11 0.3 0.1
13 0.1 0.8
9 0 15];
b = [11 9 10 1 13];
[~,ia] = sort(a(:,1));
[~,ib] = sort(b);
out = a(ia(ib),:);
ADD
[~,ia] = sort(a(:,1));
[~,ib] = sort(b);
ii = sortrows([ia(:),ib(:)],2);
out = a(ii(:,1),:);
2 Comments
See Also
Categories
Find more on Shifting and Sorting Matrices 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!