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

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.

 Réponse acceptée

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 commentaires

Could you do a quick run down of what each line does, because I am trying to get a clearer picture?
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Produits

Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by