Array, grouping elements, adding their corresponding values and sorting from left to right

1 次查看(过去 30 天)
Greetings
Im struggling with this problem. So I have an array :
X_Y=[4 7 6 9 7 10; 0.08 0.02 0.24 0.06 0.48 0.12]
and I need to group same value elements from first row and add their correspondig values from the second row. In this situation since there are two 7( 0.02+0.48). And lastly I need to sort the elements of first row in ascending order while maintaining their values from the second row.
The final array should look like this
X_Y=[4 6 7 9 10; 0.08 0.24 0.5 0.06 0.12]
How can I do this?
Thank you.

采纳的回答

David Hill
David Hill 2019-11-21
My code is a little convoluted. There is likely a better way but it works.
a=[4 7 6 9 7 6 10 6; 0.08 0.02 0.24 0.06 0.31 0.48 0.12 0.45];
[b,x]=unique(a(1,:));
y=histc(a(1,:),b)<2;
c=a(:,sort(x(y)));
d=a(1,x(~y));
for k=1:length(d)
c=horzcat(c,[d(k);sum(a(2,a(1,:)==d(k)))]);
end
[~,y]=sort(c(1,:));
c=c(:,y);
  3 个评论
David Hill
David Hill 2019-11-22
a=[4 7 6 9 7 6 10 6; 0.08 0.02 0.24 0.06 0.31 0.48 0.12 0.45];
[b,x]=unique(a(1,:));%b=[4,6,7,9,10] x=[1;3;2;4;7] the position of the first occurance
y=histc(a(1,:),b)<2;%this places 'a' into the b-bins and logically reports which bins contain only 1 count (y=[1 0 0 1 1])
c=a(:,sort(x(y)));%establish array c=[4,9,10;0.08,0.06,0.12] with no duplicates
d=a(1,x(~y));%finds values of a that have duplicates, d=[6,7]
for k=1:length(d)%cycles through the duplicates
c=horzcat(c,[d(k);sum(a(2,a(1,:)==d(k)))]);%sums row 2 of a for the duplicates and concats to the end of matrix c
end
[~,y]=sort(c(1,:));%sorts the first row of c to get indexes of the sort
c=c(:,y);%finally, sorts both rows of c based on the sort-indexes to obtain what you wanted.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

产品


版本

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by