Arrays 在Matlab中比较两列并求和值

Arrays 在Matlab中比较两列并求和值,arrays,matlab,Arrays,Matlab,我有两个这样的专栏: 0.0 1.2 0.0 2.3 0.0 1.5 0.1 1.0 0.1 1.2 0.1 1.4 0.1 1.7 0.4 1.1 0.4 1.3 0.4 1.5 在第1列中,0.0重复3次。我想对相应的元素求和 (1.2+2.3+1.5)在第2列中。同样,0.1在第1次循环中重复4次 专栏。我想在第二行中对相应的元素(1.0+1.2+1.4+1.7)求和 专栏等等 我正在这样努力 for i = 1:length(

我有两个这样的专栏:

0.0    1.2
0.0    2.3
0.0    1.5
0.1    1.0
0.1    1.2
0.1    1.4
0.1    1.7
0.4    1.1
0.4    1.3
0.4    1.5
在第1列中,0.0重复3次。我想对相应的元素求和 (1.2+2.3+1.5)在第2列中。同样,0.1在第1次循环中重复4次 专栏。我想在第二行中对相应的元素(1.0+1.2+1.4+1.7)求和 专栏等等

我正在这样努力

for i = 1:length(col1)
    for j = 1:length(col2)
        % if col2(j) == col1(i)
        % to do
        end
    end
end
给出:

s =

    5.0000    5.3000    3.9000

这是and的经典用法:

您也可以使用较新的功能代替accumarray:

[~, ~, w] = unique(x(:,1)); % labels of unique elements
result = splitapply(@sum, x(:,2), w); % sum using the above as grouping variable
x = [0.0    1.2
     0.0    2.3
     0.0    1.5
     0.1    1.0
     0.1    1.2
     0.1    1.4
     0.1    1.7
     0.4    1.1
     0.4    1.3
     0.4    1.5]; % data
[~, ~, w] = unique(x(:,1)); % labels of unique elements
result = accumarray(w, x(:,2)); % sum using the above as grouping variable
[~, ~, w] = unique(x(:,1)); % labels of unique elements
result = splitapply(@sum, x(:,2), w); % sum using the above as grouping variable