MATLAB: How to sum parts of a matrix of different sizes, without using for loops

bsxfunmatrix manipulationsumvectorization

I have a relatively large matrix NxN (N~20,000) and a Nx1 vector identifying the indices that must be grouped together. 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. I tried to find a smart vectorization method to solve the problem. I explored the arrayfun, cellfun, bsxfun functions, and looked for solutions to similar problems,… but I haven't found a final solution yet. I'll be grateful for any help! ER
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=max(idxM);
sumM=zeros(nT,nT);
for t1=1:nT
for t2=1:nT
sumM(t1,t2)=sum(sum(M(idxM==t1,idxM==t2)));
end
end
PS: Long-term reader, first-time poster.

Best Answer

S=sparse(1:N,idxM,1);
sumM=S.'*(M*S);