Matlab multiply matrix with matrix along third dimension

I have a A

size matrix m x n x 3

and I have a matrix 3x3

K

. Now I want to do something like this:

for row = 1:m
 for col = 1:n
  A(row,col,:) = K*[A(row,col,1);A(row,col,2);A(row,col,3)];
 end
end

      

I want to have an efficient solution without a loop as loops are very slow because that is m x n

usually the size of the image.

Anyone got an idea?

+3


source to share


1 answer


M = 1000;
N = 1000;
L = 3;
A = rand(M,N,L);
K = rand(L,L);
Q = reshape((K * reshape( A, [M*N, L] ).' ).', [M, N, L]);

      

Error checking:



Z = zeros(M,N,L);
for mm = 1 : M
  for nn = 1 : N
    Z(mm,nn,:) = K * squeeze( A(mm,nn,:) );
  end
end
max( abs( Z(:) - Q(:) ) )

ans =

      0

      

+4


source







All Articles