Efficient matrix operation: how to avoid for loop

조회 수: 3 (최근 30일)
Roberto
Roberto 2019년 12월 24일
댓글: Roberto 2019년 12월 24일
Hi all,
I need to speed up a matrix operation and don't know how.
Here's a toy example of what I need to do:
A = randi(10,[4,10])
A =
3 8 8 5 1 1 9 9 4 2
8 9 4 3 4 10 5 8 8 7
4 1 2 10 1 5 2 6 1 2
1 7 1 5 4 7 3 10 1 4
B = randi(10,[2,10])
B =
3 3 4 10 3 7 5 6 8 8
8 1 4 8 8 6 10 5 8 5
C = zeros(size(A,1),size(B,1),size(B,2));
for i = 1:size(B,2)
C(:,:,i) = A(:,i).*B(:,i)';
end
C(:,:,1)
ans =
9 24
24 64
12 32
3 8
In other words C is a 3 dimensional tensor and C(:,:,i) is a matrix in which the column k is A(:,i)*C(k,i).
How can I compute C (or compute and store the same informations of C in some other way) in a more efficient way, possibly avoiding the for loop?
Thanks

채택된 답변

Allen
Allen 2019년 12월 24일
Roberto, this should help with consolidating your code as well as improving the overall performance. Benchtests that I ran were orders of magnitude faster when comparing to size(A) = [4, 1e+6] and size(B) = [2, 1e+6].
C = reshape(A,[size(A,1),1,size(A,2)]).*reshape(B,[1,size(B)]);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by