如何在不使用for循环的情况下求和不同大小的矩阵的各个部分? [英] How to sum parts of a matrix of different sizes, without using for loops?
问题描述
我有一个相对较大的矩阵NxN(N〜20,000)和一个Nx1向量,用于标识必须分组在一起的索引.
I have a relatively large matrix NxN (N~20,000) and a Nx1 vector identifying the indices that must be grouped together.
我想将矩阵的各个部分加在一起,原则上可以有不同数量的元素和不相邻的元素. 我很快写了一个双for循环,它可以正常工作,但是效率很低.探查器将这些循环识别为我的代码中的瓶颈之一.
I want to sum together parts of the matrix, which in principle can have a different number of elements and non-adjacent elements. I quickly wrote a double for-loop that works correctly but of course it is inefficient. The profiler identified these loops as one of the bottlenecks in my code.
我试图找到一种智能的矢量化方法来解决该问题.我研究了arrayfun
,cellfun
和bsxfun
函数,并寻找解决类似问题的方法...但是我还没有找到最终的解决方案.
I tried to find a smart vectorization method to solve the problem. I explored the arrayfun
, cellfun
, and bsxfun
functions, and looked for solutions to similar problems... but I haven't found a final solution yet.
这是带有两个for循环的测试代码:
This is the test code with the two for-loops:
M=rand(10); % test matrix
idxM=[1 2 2 3 4 4 4 1 4 2]; % each element indicates to which group each row/column of M belongs
nT=size(M,1);
sumM=zeros(max(idxM),max(idxM));
for t1=1:nT
for t2=1:nT
sumM(t1,t2) = sum(sum(M(idxM==t1,idxM==t2)));
end
end
推荐答案
我想指出对其他论坛提供的答案感兴趣的人
I'd like to point those who are interested to this answer provided on another forum
S=sparse(1:N,idxM,1);
sumM=S.'*(M*S);
S=sparse(1:N,idxM,1);
sumM=S.'*(M*S);
信用(和有用的讨论):
Credits (and useful discussion):
这篇关于如何在不使用for循环的情况下求和不同大小的矩阵的各个部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!