4
votes

Given two vectors r and c that hold row and column subscripts into a matrix A (its size also given), I want to compute A. Points can occur multiple times and should increment the corresponding element in A for every occurence. An example:

r = [1 2 4 3 2];
c = [2 2 1 1 2];
A = zeros(4, 3);

ind = sub2ind(size(A), r, c);
for i = 1 : length(ind)
    A(ind(i)) = A(ind(i)) + 1; % could as well use r and c instead of ind ...
end

This yields the matrix

A =
     0     1     0
     0     2     0
     1     0     0
     1     0     0

I'd like to avoid the loop if possible. Is there a vectorized solution to this problem? Preferably one that does not generate huge temporary matrices ...

1

1 Answers

5
votes

This is a job for accumarray:

r = [1 2 4 3 2];
c = [2 2 1 1 2];

%# for every r,c pair, sum up the occurences
%# the [4 3] is the array size you want
%# the zero is the value you want where there is no data
accumarray([r',c'],ones(length(r),1),[4 3],@sum,0)

ans =

     0     1     0
     0     2     0
     1     0     0
     1     0     0

Note that if your resulting array has so many zeros (i.e. is very sparse), sparse may be the better option, as suggested by @woodchips

sparse(r,c,ones(size(r)),4,3)

ans =

   (3,1)        1
   (4,1)        1
   (1,2)        1
   (2,2)        2