Sort and add value from same neighbour value

1 次查看(过去 30 天)
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