Efficient matrix operation: how to avoid for loop
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
Allen
am 24 Dez. 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)]);
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!