Sort and add value from same neighbour value

조회 수: 1 (최근 30일)
yue ishida
yue ishida 2017년 7월 5일
답변: Rik 2017년 7월 5일
I have a calculation problem and need anyone help to solve it.
out =
'Q7' [ 0] 'Q12G' [ 0] 'Q12G' [ 0] 'Q7' [ 0] 'Q12G' [ 0] 'Q12G' [ 0]
'Q12H' [-3] 'Q12L' [-3] [] [] [] [] [] [] [] []
1. I have 12 columns. First, I want to combine column 1&2,5&6,9&10 in cell A
A=
'Q7' [ 0]
'Q12H' [-3]
'Q12G' [ 0]
[] []
'Q12G' [ 0]
[] []
2. Then, I want to combine column 3&4,7&8,11&12 in cell B
B=
'Q12G' [ 0]
'Q12L' [-3]
'Q7' [ 0]
[] []
'Q12G' [ 0]
[] []
My question is, can we sort cell A and B, then add right column values of same left column values, and merge them become one value only instead of occur multiple times.
The output will become like this.
newA=
'Q7' [0]
'Q12H' [-3]
'Q12G' [0]
newB=
'Q12G' [0]
'Q12L' [-3]
'Q7' [0]
Thank you for your help.

채택된 답변

Rik
Rik 2017년 7월 5일
If I am parsing your question correctly you're asking how you can remove empty lines from a cell and sum the values in the second column for duplicate indices in the first column. Is this correct? If so, you can use unique to find duplicate indices.
A={'Q7',0;'Q12H',-3;'Q12G',0;[],[];'Q12G',0;[],[]};
%look here: https://www.mathworks.com/matlabcentral/answers/42283-index-non-empty-cells-in-cell-array#comment_86674
empty_idx=cellfun('isempty', A(:,1));
A=A(~empty_idx,:);%remove empty cells
second_col=cell2mat(A(:,2));
[a,~,c]=unique(A(:,1));
for n=1:length(a)%loop over all positions
a{n,2}=sum(second_col(c==n));
end
Please note that the loop will be very inefficient if A gets large.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by