How can I sort an array of repeating elements
1 次查看(过去 30 天)
显示 更早的评论
Hi
I have the following array (20 by 2). The 1st column is node number and 2nd is temperature. The temperature is in descending order. There are 6 different values of temperatures. How can I sort this array such that it outputs;
set1 temp=670K nodes=10,14,15
set2 temp=668K nodes=385,431,432,440,441,442
set3 temp=655K nodes=649,650,959,960,961
set4 temp=654K nodes=80
set5 temp=653K nodes=89,90,651,652
set6 temp=646K nodes=646
ARRAY:
10 670.0
14 670.0
15 670.0
385 668.0
431 668.0
432 668.0
440 668.0
441 668.0
442 668.0
649 655.0
650 655.0
959 655.0
960 655.0
961 655.0
80 654.0
89 653.0
90 653.0
651 653.0
652 653.0
79 646.0
I hope the above is clear. Let me know if its not.
Thanks in advance.
Mohan
4 个评论
Image Analyst
2013-4-2
So the output is a cell array of strings:
ca{1} = 'set1 temp=670K nodes=10,14,15'
ca{2} = 'set2 temp=668K nodes=385,431,432,440,441,442'
ca{3} = 'set3 temp=655K nodes=649,650,959,960,961'
ca{4} = 'set4 temp=654K nodes=80'
ca{5} = 'set5 temp=653K nodes=89,90,651,652'
ca{6} = 'set6 temp=646K nodes=646'
or if you don't actually want to store those strings, then just print them out to the command line or a text file? Please define exactly what and where "outputs" means.
回答(3 个)
Image Analyst
2013-4-1
Did you try sortrows():
% Sort by column 2 in descending order.
sortedArray = sortrows(ARRAY, -2)
0 个评论
Brian B
2013-4-1
It depends how you want to store the sets. If you are comfortable with cell arrays, you can create one vector with the unique temperatures, and then create a cell array of the same size such that each cell has the set of nodes withe the corresponding temperature:
temperatures = unique(ARRAY(:,2));
nodes = arrayfun(@(temp)ARRAY(ARRAY(:,2)==temp, 1),temperatures,'UniformOutput',0)
0 个评论
Andrei Bobrov
2013-4-1
a = [10 670.0
14 670.0
15 670.0
385 668.0
431 668.0
432 668.0
440 668.0
441 668.0
442 668.0
649 655.0
650 655.0
959 655.0
960 655.0
961 655.0
80 654.0
89 653.0
90 653.0
651 653.0
652 653.0
79 646.0];
[b, ~, c] = unique(a(:,2),'stable');
out = [num2cell((1:max(c2))') num2cell(b) accumarray(c2,a(:,1),[],@(x){x})];
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!