MATLAB: Sum of rows if elements in the first columns are same

sum

Hello Guys, i have to do a sum operation on a matrix. for example x = [1 2 3 4 5 6; 1 3 5 7 9 11; 2 3 4 5 6 7; 2 4 6 8 10 12]
i need to check if the row elements in the first column are equal, if equal then add the rows together. the answer below is what i expect
x_sum = [1 5 8 11 14 17; 2 7 10 13 16 19].
It would be great if you guys can help. Thanks Raj

Best Answer

One of many ways:
x = [1 2 3 4 5 6; 1 3 5 7 9 11; 2 3 4 5 6 7; 2 4 6 8 10 12];
[uv,~,idx] = unique(x(:,1));
nu = numel(uv);
x_sum = zeros(nu,size(x,2));
for ii = 1:nu
x_sum(ii,:) = sum(x(idx==ii,:));
end