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 Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by