Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to add up values in different rows

1 view
Skip to first unread message

Shima

unread,
Jul 1, 2009, 3:43:01 PM7/1/09
to
I have a "n x 3" matrix. I want a code where it checks the first and second columns and if they are equal then it adds up the correponding values in the third column.

A=[1 2 3; 1 2 5; 1 2 3;...
1 3 1; 1 3 1; 2 1 1;...
2 1 1; 2 1 2; 2 1 2]

then the result will be:

B=[1 2 11; 1 3 2; 2 1 6]

My own code is :
m=length(A);
for i=1:m-1
if A(i,1)==A(i+1,1) && A(i,2)==A(i+1,2)
A(i,3)=A(i,3)+A(i+1,3)
else
A(i,3)=A(i,3)
end
end

But it's not working!
I appreciate if you could help me!

us

unread,
Jul 1, 2009, 3:57:03 PM7/1/09
to
"Shima " <khanm...@gmail.com> wrote in message <h2ge85$djd$1...@fred.mathworks.com>...

one of the many solutions

ac=accumarray(A(:,1:2),A(:,3));
[ir,ic,iv]=find(ac.'); % <- note the transpose...
r=[ic,ir,iv]
%{
% r =


1 2 11
1 3 2
2 1 6

%}

us

Shima

unread,
Jul 1, 2009, 4:30:20 PM7/1/09
to
Hi us;
Thanks for the reply. I tried this, but it only works when the inputs are integers. If the values are real number then It won't work!
A=[1.11 2.20 3.00; 1.11 2.20 5.00; 1.11 2 .20 3.00;...
1.00 3.00 1.00; 1.00 3.00 1.00; 2.00 1.00 1.00;...].

:(...


Shima

unread,
Jul 1, 2009, 4:37:01 PM7/1/09
to
Hi,
Thanks for your reply.
I tried this, but unfortunately it only works with integers, if the elements are real numbers then it gives error
:(

"us " <u...@neurol.unizh.ch> wrote in message <h2gf2f$6n5$1...@fred.mathworks.com>...

Jos

unread,
Jul 1, 2009, 4:43:02 PM7/1/09
to
"Shima " <khanm...@gmail.com> wrote in message <h2gh0s$dvr$1...@fred.mathworks.com>...

Try this:

[UnA,dum,idx] = unique(A(:,1:2),'rows')
V = accumarray(idx,A(:,3)) ;
Result = [UnA V]

hth
Jos

Shima

unread,
Jul 1, 2009, 4:59:02 PM7/1/09
to
Thanks Jos,
This code is working...
:)
0 new messages