Speeding up a loop.
Show older comments
Hello, I hope you are well. I have the following two loops
With 'a' having the dimention 4*n1*n1
for i=1:n1
for j=1:n1
for k=1:n1
for h=1:n1
b(i,j,k,h)=sum(a(1,i,:).*a(2,j,:).*a(3,k,:).*a(4,h,:));
end
end
end
end
and a simmilar loop for d=5
for i=1:n1
for j=1:n1
for k=1:n1
for h=1:n1
b(i,j,k,h)=sum(a(1,i,:).*a(2,j,:).*a(3,k,:).*a(4,h,:).*a(5,l,:);
end
end
end
end
Is there anyway to speed up these loops or vectorize the code?
Answers (1)
Hassaan
on 10 Jan 2024
For d=4:
% Vectorized operation for d=4 with implicit expansion
b = sum(a(1,:,:,:) .* ...
permute(a(2,:,:,:), [1, 3, 2, 4]) .* ...
permute(a(3,:,:,:), [1, 4, 3, 2]) .* ...
permute(a(4,:,:,:), [1, 4, 2, 3]), 4);
For d=5:
% Vectorized operation for d=5 with implicit expansion
b = sum(a(1,:,:,:) .* ...
permute(a(2,:,:,:), [1, 3, 2, 4, 5]) .* ...
permute(a(3,:,:,:), [1, 5, 3, 2, 4]) .* ...
permute(a(4,:,:,:), [1, 5, 4, 2, 3]) .* ...
permute(a(5,:,:,:), [1, 5, 4, 3, 2]), 5);
In these examples, the permute function is used to reorder the dimensions of the array a so that when you multiply them, they are correctly aligned for element-wise multiplication, and sum is used to aggregate along the specified dimension.
Make sure to replace the n1 with the actual size and a with the actual array you're working with. These operations are quite memory-intensive due to the large size of the resulting array b, so ensure that your machine has enough resources to handle the computation.
---------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
Professional Interests
- Technical Services and Consulting
- Embedded Systems | Firmware Developement | Simulations
- Electrical and Electronics Engineering
Feel free to contact me.
2 Comments
That doesn't appear to give the same result as OP's code:
d = 4;
n1 = 2;
a = reshape(1:d*n1*n1,[],n1,n1);
b = zeros(n1,n1,n1,n1);
for i=1:n1
for j=1:n1
for k=1:n1
for h=1:n1
b(i,j,k,h)=sum(a(1,i,:).*a(2,j,:).*a(3,k,:).*a(4,h,:));
end
end
end
end
disp(b)
b = sum(a(1,:,:,:) .* ...
permute(a(2,:,:,:), [1, 3, 2, 4]) .* ...
permute(a(3,:,:,:), [1, 4, 3, 2]) .* ...
permute(a(4,:,:,:), [1, 4, 2, 3]), 4);
disp(b)
JM
on 12 Jan 2024
Categories
Find more on Programming 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!