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 …
This is a job for
accumarray:Note that if your resulting array has so many zeros (i.e. is very sparse),
sparsemay be the better option, as suggested by @woodchips