给定两个向量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
Run Code Online (Sandbox Code Playgroud)
这产生了矩阵
A =
0 1 0
0 2 0
1 0 0
1 0 0
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我想避免循环.是否存在针对此问题的矢量化解决方案?最好不会产生巨大的临时矩阵......
这是一份工作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
Run Code Online (Sandbox Code Playgroud)
请注意,如果您生成的数组有这么多零(即非常稀疏),sparse可能是更好的选择,如@woodchips所示
sparse(r,c,ones(size(r)),4,3)
ans =
(3,1) 1
(4,1) 1
(1,2) 1
(2,2) 2
Run Code Online (Sandbox Code Playgroud)