how to vectorize 4 for loops with several index combinations?
Show older comments
I have the following 4 for loops, which recombine the components of a tensor B into a new tensor A, and I need to vectorize these loops to cut runtime. How can that be done? This should be a great exercise to finally understand how to vectorize whatever loops. I think we should probably use the function ndgridVecs to create a grid. What is not clear to me yet is how one should recombine the indices according to the rule in the core inner loop. I would probably eventually get there by myself, but I really don't have a lot of time available for this now. I would be grateful if someone could help me with this.
B = rand(3,3,3,3)
A = zeros(size(B));
for i=1:3
for j=1:3
for k=1:3
for l=1:3
A(i,j,k,l) = 10*...
(B(k,i,j,l) ...
+ B(k,j,i,l) ...
+ B(l,i,j,k) ...
+ B(l,j,i,k));
end
end
end
end
1 Comment
Matt J
on 13 Feb 2024
It would advisable to show the typical dimensions rather than a 3x3x3x3 example. The recommendation can depend on what the true sizes will be.
Accepted Answer
More Answers (0)
Categories
Find more on Logical 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!