将下标矢量化为矩阵转换

时间:2012-04-18 18:57:19

标签: matlab

给定两个向量r和c,它们将行和列下标保存到矩阵A(它的大小也给出),我想计算A.点可以多次出现,并且应该在每次出现时增加A中的相应元素。一个例子:

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

这产生矩阵

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

如果可能,我想避免循环。是否存在针对此问题的矢量化解决方案?最好不会产生巨大的临时矩阵...

1 个答案:

答案 0 :(得分:5)

这是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

请注意,如果生成的数组有这么多零(即非常稀疏),{@ 1}}可能是更好的选择,正如@woodchips所建议的那样

sparse