Paul
Paul

Reputation: 31

Vectorization for array multiplication

I have an 3d array U, and a 2d matrix A. I want to do the multiplication like following way. How can I vectorize my code? The loop is too slow, of course.

for j=1:N
 for k=1:N
 UU(:,j,k)=A*U(:,j,k);
 end
end

Upvotes: 2

Views: 77

Answers (2)

Phil Goddard
Phil Goddard

Reputation: 10772

Depending on the size of your matrices, you might find that eliminating both loops chews up a lot of memory, and that removing just the loop over the columns is sufficient,

for k = 1:N
   UU(:,:,k) = A*U(:,:,k);
end

Upvotes: 0

Divakar
Divakar

Reputation: 221614

Reshape U to 2D and perform the matrix-multiplication, thus reducing the first axis/dimension of U with A's last axis to give us a 2D array. Finally, reshape back to 3D for the final result, like so -

[m1,n1] = size(A);
[~,m2,n2] = size(U);
out = reshape(A*reshape(U,[n1,m2*n2]),[m1,m2,n2])

Upvotes: 2

Related Questions