Vectorizing tensor-matrix product - for-loop is faster??
Afficher commentaires plus anciens
Hi All. I am trying to calculate a tensor-matrix inner product in the following code. I need
K(i,a,k,b) = C(i,J,k,L)*N(a,J)*N(b,L) where we sum over repeated indices.
I did it using for-loop and using reshape() and shiftdim() and timed both versions. I get for-loop to be faster.
clear;clc;
% Inner-product test
C = rand(2,2,2,2);
N = rand(3,2);
tic;
% Using for-loop
K_for = zeros(2,3,2,3);
for i=1:2
for a=1:3
for k=1:2
for b=1:3
for J=1:2
for L=1:2
K_for(i,a,k,b) = K_for(i,a,k,b) +...
C(i,J,k,L)*N(a,J)*N(b,L);
end
end
end
end
end
end
toc;
tic;
% Using permute and reshape
[n1,n2,n3,n4] = size(C);
[a,b] = size(N);
K = reshape(C,n1*n2*n3,n4)*N.';
K = reshape(K,[n1,n2,n3,a]);
K = shiftdim(K,2);
K = reshape(K,n3*a*n1,n2)*N.';
K = reshape(K,[n3,a,n1,a]);
K = shiftdim(K,2);
toc;
My tic-toc outputs are:
Elapsed time is 0.000035 seconds. <-- For for-loop version
Elapsed time is 0.009384 seconds. <-- For vectorized version
Is there a more efficient way of vectorizing inner products?
Regards,
Amit
Réponses (0)
Catégories
En savoir plus sur Matrices and Arrays dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!