3
votes

I have a matrix A of size m x n x 3 and I have have a 3x3 matrix K. Now what I want to do is 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'd like to have an efficient solution without a loop, as loops are very slow, because m x n is usually the size of an image.

Anyone got an idea?

1

1 Answers

4
votes
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 check:

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