How can I sort the output matrix according to the prescribed order in a column?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
dpb
2013-7-6
编辑:dpb
2013-7-7
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 个评论
dpb
2013-7-7
_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
2013-7-7
编辑:Andrei Bobrov
2013-7-8
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),:);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!