如何对每个细胞子部分的各列进行求和? 给定一个单元格A
A = {'a' '546.8' '543.5' '544'
'a' '641.9' '637.4' '632.3'
'a' '214.7' '214.1' '231.8'
'a' '256.9' '255.6' '254.2'
'c' '356' '355.1' '354.4'
'c' '759' '759.6' '756.2'
'c' '352.2' '350.4' '350.8'
'f' '234' '230.3' '232.3'
'f' '225' '223.5' '221.8'}
根据A的第一列中的不同字母将A分成子单元格。并且对子单元格的每列进行求和。
预期结果是:
B = {'a' '1660.3' '1650.6' '1662.3'
'c' '1467.2' '1465.1' '1461.4'
'f' '459' '453.8' '454.1'}
答案 0 :(得分:3)
不需要循环:
%// get unique rows
[ids,~,subs] = unique(A(:,1))
%// transform string data to numeric data
vals = str2double(A(:,2:end))
%// sum unique rows
sums = accumarray(subs, 1:numel(subs), [], @(x) {sum(vals(x,:),1)} )
%// output result
out = [ids(:),num2cell(cell2mat(sums))]
答案 1 :(得分:2)
可能的解决方案之一是
[B,~,idxs]= unique(A(:,1))
for k=2:size(A,2)
B(:,k)= num2cell(accumarray(idxs,str2double(A(:,k))))
end