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

1 view (last 30 days)
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

Accepted Answer

Ameer Hamza
Ameer Hamza on 18 Jun 2020
Edited: Ameer Hamza on 18 Jun 2020
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.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!