Vectorizing tensor outer product using permute is slower than for-loop
1 view (last 30 days)
Show older comments
Hi Everyone. I have the following code for computing outer products of two second-order tensors to get a fourth-order tensor. I did it using for-loops. I also attempted to vectorize using permute and bsxfun. I timed both versions. But the for-loop turns out to be faster. I am not able to understand if there is a better way to vectorize.
clear;
clc;
F = rand(200); %I run out of memory in bsxfun() for larger 2D arrays
C_for = zeros(3,3,3,3);
tic;
for l=1:3
for M=1:3
for n=1:3
for O=1:3
C_for(l,M,n,O) = F(M,l)*F(O,n);
end
end
end
end
toc;
tic;
A = permute(F,[2,1,3,4]);
B = permute(F,[3,4,2,1]);
C_vec = bsxfun(@times,A,B);
toc;
My output for tic-toc is:
For loop: Elapsed time is 0.000289 seconds
Vectorized: Elapsed time is 8.725277 seconds
Any suggestions to improve the vectorization?
Regards,
Amit
0 Comments
Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!