필터 지우기
필터 지우기

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