MATLAB: Multiplying a 2-D array to a specific dimension of a 3-D matrix

3-d matrix multiplicaiton

Hello. I'm trying to multiply a two dimentioanl array to a specific dimension of a 3-D matrix. For example, A=[2000*2000*72], B=[72*3] and I'm trying to reach
C=[2000*2000*3]. In other words B should be multiplied to the 3rd dimension of A and repeated (element wise) for 2000*2000 points in the first two dimensions. Currently I'm using a loop like this:
for ii=1:size(A,1)
for jj=1:size(A,2)
A1=A(ii,jj,:);
A1=A1(:);
C1=B'*A1; % C1 has dimension of 3*1
C2=D*C1; %D is a 3-3 matrix therefore, C2 has the same dimension as C1
C(ii,jj,:)=C2(:,1);
end
end
Is there a simple way to write this? I would rather avoid complications using "for loop".
Thanks, Cameron

Best Answer

Try something like this
A = rand(100, 100, 72);
B = rand(72, 3);
A_C = mat2cell(A, ones(size(A,1),1), ones(size(A,2),1), size(A,3));
C = cell2mat(cellfun(@(x) {reshape(squeeze(x).'*B, 1, 1, [])}, A_C));
Although I guess that the solution using for-loop will be much faster.