# Efficient matrix operation: how to avoid for loop

16 views (last 30 days)
Roberto on 24 Dec 2019
Commented: Roberto on 24 Dec 2019
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 on 24 Dec 2019
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)]);
Roberto on 24 Dec 2019
Thank you!