How to reorder the rows by sorting the elements of column in ascending order?
2 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
I have id=[ 1 3 2; 2 6 4; 3 2 6; 4 5 1; 5 1 3; 6 4 5; 7 7 7]
j=1:3
I want to reorder the rows of id by sorting the jth column of id such that the elements in this column are sorted from small to large.
Where my result will get j set of number.
id1=[ 1 3 2; 2 6 4; 3 2 6; 4 5 1; 5 1 3; 6 4 5; 7 7 7]
id2=[5 1 3; 3 2 6; 1 3 2; 6 4 5; 4 5 1; 2 6 4; 7 7 7]
id3=[4 5 1; 1 3 2; 5 1 3; 2 6 4; 6 4 5; 3 2 6; 7 7 7 ]
How can i do this?
Thanks.
0 个评论
采纳的回答
dpb
2014-5-13
编辑:dpb
2014-5-13
for c=1:3
is(1)={sortrows(id,i)};
end
using a cell array to hold results; use a dynamic named structure field if desired
Alternatively, arrayfun is your friend for such things...
idsrted=arrayfun(@(c) sortrows(id,c),[1:3],'uniform',0);
4 个评论
dpb
2014-6-2
for c=1:3
new_id=sortrows(id,c);
...if use this as an example, the output will give me three different new_id...
NO! It'll give you only one new_id; the last one. Each subsequent pass thru the loop overwrites the previous as you didn't increment a cell array or concatenate the results to the existing in a single larger array.
Again, it's not clear just what you're after--if doesn't matter how large the array is as to the logic; the question remains on whether you must have the results all at once or can do the process on each subset at a time. We can't answer that; that depends on the results required. The thing I wonder about is why do sortrows individually if the latter; why not concatenate the full dataset then sort only once at the end? Bound to be more efficient.
更多回答(1 个)
Andrei Bobrov
2014-5-13
[~,ii] = sort(id);
id_out = bsxfun(@(a,b)a(b,:),id,permute(ii,[1 3 2]));
0 个评论
另请参阅
类别
在 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!