fast solution for matrix multiplication
조회 수: 1 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Guillaume
2017년 5월 28일
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
Guillaume
2017년 5월 30일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!