How can I sort an array of repeating elements
2 views (last 30 days)
Show older comments
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 Comments
Image Analyst
on 2 Apr 2013
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.
Answers (3)
Image Analyst
on 1 Apr 2013
Did you try sortrows():
% Sort by column 2 in descending order.
sortedArray = sortrows(ARRAY, -2)
0 Comments
Brian B
on 1 Apr 2013
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 Comments
Andrei Bobrov
on 1 Apr 2013
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 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!