MATLAB: How to add matrices stored in a cell structure

cellfor loopsum

Dear Mathworks community,
I want to add a large number of sparse matrices the fastest way possible. The matrices are stored in a cell structure (A). Furthermore, there is always a vector to weight the terms of the sum (weights)
Right now, I am using a for-loop, as done in the example below. Is there a way to avoid the for-loop to make the calculation faster?
tic
% Define empty matrix for the result
A_sum = sparse(zeros(1000));
% Define a cell structure to store matrices to be added
A = cell(10,1);
% Fill the cell structure with random sparse matrices
for index = 1:10
A{index} = sprand(1000,1000,0.001);
end
% Define weights for sum
weights = [0, 0, 0, 0.5, 0, 0, 0.2, 0, 0, 0.1];
% Detect the elements that appear in the sum
IndexWeights = find(weights>0);
% Calculate the sum with a for loop
for LocInd = 1:length(IndexWeights)
A_sum = A_sum + weights(IndexWeights(LocInd))*A{IndexWeights(LocInd)};
end
toc

Best Answer

This would be slightly more efficient:
% Detect the elements that appear in the sum
IndexWeights = find(weights>0);
% Calculate the sum with a for loop
A_sum = weight(IndexWeights(1)) .* A(IndexWeights(1)) ;
for LocInd = IndexWeights(2:end)
A_sum = A_sum + weights(LocInd) .* A{LocInd} ;
end