Sum of rows if elements in the first columns are same

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

댓글 수: 3

What have you tried so far?
I tried with Cumsum and Sum but wasnt able to get any where close. I can do it using loops but before using loops wanted to ask you guys the experts whether this can be done without loops....
José-Luis
José-Luis 2012년 12월 14일
편집: José-Luis 2012년 12월 14일
Is there a particular reason you don't want loops, they are not intrinsically bad and can actually be faster than other approaches. Please show what you have done so we can guide you.

댓글을 달려면 로그인하십시오.

 채택된 답변

Sean de Wolski
Sean de Wolski 2012년 12월 14일
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

댓글 수: 1

Sean, Thanks for the answer works great, to have the set of data as per my answer i changed a little bit the answer above, but it is a great solution. Thanks Raj
My changed code is as below
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,1) = uv(ii,1);
x_sum(ii,2:size(x,2)) = sum(x(idx==ii,2:size(x,2)));
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

태그

질문:

2012년 12월 14일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by