An student
An student

Reputation: 392

Comparing two columns and summing the values in Matlab

I have 2 columns like this:

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

In the 1st column, 0.0 is repeated 3 times. I want to sum corresponding elements (1.2 + 2.3 + 1.5) in the 2nd column. Similarly, 0.1 is repeated 4 times in the 1st column. I want to sum the corresponding elements (1.0 + 1.2 + 1.4 + 1.7) in the 2nd column and so on.

I am trying like this

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

Upvotes: 2

Views: 107

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

This is a classical use of unique and accumarray:

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

You can also use the newer splitapply function instead of accumarray:

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

Upvotes: 6

Ander Biguri
Ander Biguri

Reputation: 35525

a=[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]
% Get unique col1 values, and indices
[uniq,~,ib]=unique(a(:,1));

% for each unique value in col1
for ii=1:length(uniq)
    % sum all col2 values that correspond to the current index of the unique value
    s(ii)=sum(a(ib==ii,2));
end

Gives:

s =

    5.0000    5.3000    3.9000

Upvotes: 2

Related Questions