fast solution for matrix multiplication
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
I have the following expression of the matrix elements B_(l,m):
B_(l,m)=Sum(over k=0 to N) of a_(l,k)*a_(m,k+1)+a_(l,k+1)*a_(m,k);
- N is a number between 10-1000
- a_(l,k) is a matrix of size N*N
my approach was to go with a loop over the columns of a_(l,k)
(multiplying each column of a_(l,k) by the entire matrix a_(m,k))
for i=1:N
a_lmk=a_lnk(k+1,i).*a_lk(k+2,:)+a_lk(k+2,i).*a_lk(k+1,:);
B_lm(i,:)=sum(a_lmk);
end
Is there a direct and faster method to calculate it?
I'm attaching a picture to clarify the expression (I can handle with the prefactors 2,(k+1)./...).
0 Kommentare
Antworten (1)
Guillaume
am 28 Mai 2017
This should work:
k = 1:N-1;
kcoeffs = k ./ (2*k-1) ./ (2*k+1);
%R2016b or later
B = squeeze(sum(2*kcoeffs .* (A(:, 1:end-1) .* permute(A(:, 2:end), [3 2 1]) + A(:, 2:end) .* permute(A(:, 1:end-1), [3 2 1])), 2))
%R2015b and earlier:
B = squeeze(sum(bsxfun(@times, 2*kcoeffs, ...
bsxfun(@times, A(:, 1:end-1), permute(A(:, 2:end), [3 2 1])) + ...
bsxfun(@times, A(:, 2:end), permute(A(:, 1:end-1), [3 2 1]))), 2))
2 Kommentare
Guillaume
am 30 Mai 2017
Yes, you will temporarily need around 8 GB of memory for the product when N = 1000. I'm afraid it's a trade-off between speed and memory. If you don't have enough memory, you'll have to go with a slower loop.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!