比较两列并在Matlab中求和值

An *_*ent 2 arrays matlab

我有2个这样的列:

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
Run Code Online (Sandbox Code Playgroud)

在第1列中,0.0重复3次.我想在第二列中总结相应的元素(1.2 + 2.3 + 1.5).类似地,在第1列中重复0.1次.我想在第二列中总结相应的元素(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
Run Code Online (Sandbox Code Playgroud)

Lui*_*ndo 6

这是经典的使用uniqueaccumarray:

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
Run Code Online (Sandbox Code Playgroud)

您也可以使用较新的splitapply功能而不是accumarray:

[~, ~, w] = unique(x(:,1)); % labels of unique elements
result = splitapply(@sum, x(:,2), w); % sum using the above as grouping variable
Run Code Online (Sandbox Code Playgroud)