ömer çel
ömer çel

Reputation: 23

Matlab add rows if they have similar values

I am newbie in matlab, I just can not understand what is wrong in my matlab code.

Firstly, I would like to add rows values if other values are same,

for example for the input of x,

x=[ 1 1; 
    1 2;
    2 1;
    3 1;
    3 1 ] 

I would like to be able to return my function as,

z=[1 3;
   2 1;
   3 2]

my code:

x=[1 1;1 3;1 0;3 1;3 5;4 7;4 5];
z=[];
i=1;
a=0;
k=1;
sum=x(1,2);
[sizex,n]=size(x);
%fprintf('m-k --->%d\n',sizex-k);
while i<=(sizex-k)

    if(x(i,1)== x(i+k,1))


        sum=x(i+k,2)+sum;
        k=k+1;

    elseif (x(i,1)~= x(i+k,1))

        z(1+a,1)=x(i,1);
        z(1+a,2)=sum;
        sum=x(i+k,2);
        i=i+k;
        k=1;
        a=a+1;
    end

end

I would be very appraciated if I can get the answer. Thanx in advance

Upvotes: 2

Views: 56

Answers (1)

gnovice
gnovice

Reputation: 125854

This can be accomplished by using unique to get a list of unique identifiers from your first column and then using accumarray to add up the totals from the second column for each unique identifier:

x = [1 1; 1 2; 2 1; 3 1; 3 1];
[vals, ~, index] = unique(x(:, 1), 'stable');
z = [vals accumarray(index, x(:, 2))];

z =
     1     3
     2     1
     3     2 

Upvotes: 1

Related Questions