How to multiply a 3d array with a 2d matrix?

7 views (last 30 days)
I have a 3D array of size [1000, 128,64] where 1st dimension is the number of samples (1000). I want to multiply each of these matrix in mtx_a with a 2D matrix of size [ 64, 15] in mtx_b and save it into a 3D array mtx_c again [1000,128,15]. I tried the following code and got the error "Arrays have incompatible sizes for this operation. line 5 : mtx_c(:,i,j) = mtx_a(:,i,j) .* mtx_b;".
Thank you in advance.
load mtx_a.mat;
load mtx_b.mat;
for i = 1:size(mtx_a,2)
for j = 1:size(mtx_b,3)
mtx_c(:,i,j) = mtx_a(:,i,j) .* mtx_b;
end
end
save mtx_c.mat mtx_c '-v7.3';

Accepted Answer

Torsten
Torsten on 8 Jul 2022
Edited: Torsten on 8 Jul 2022
Just the other way round:
mtx_c = zeros(size(mtx_a,1),size(mtx_a,2),size(mtx_b,2));
for i = 1:size(mtx_a,1)
M = squeeze(mtx_a(i,:,:));
mtx_c(i,:,:) = M*mtx_b;
end

More Answers (2)

Voss
Voss on 8 Jul 2022
% Initialize array mtx_c
[N,M,~] = size(mtx_a);
P = size(mtx_b,2);
mtx_c = zeros(N,M,P);
% mtx_a must be permuted to 128x64x1000 so that each slice (in dimension 3) is 128x64 (2D)
% without permuting, each slice (in dimension 1) would be 1x128x64 (3D)
mtx_a_temp = permute(mtx_a,[2 3 1]);
% calculate mtx_c
for i = 1:size(mtx_a,1)
mtx_c(i,:,:) = mtx_a_temp(:,:,i)*mtx_b;
end
  2 Comments

Sign in to comment.


James Tursa
James Tursa on 8 Jul 2022
Edited: James Tursa on 8 Jul 2022
It would be best if your 2D pages were the first two dimensions. That way the 2D pages are contiguous in memory and you can use one of several functions to do the 2D page matrix multiplies. E.g., using the MATLAB function pagemtimes:
mtx_a = your [1000, 128,64] size array
mtx_b = your [64, 15] size matrix
mtx_p = permute(mtx_a,[2,3,1]); % mtx_a array permuted to be size 128x64x1000
mtx_c = pagemtimes(mtx_p,mtx_b);
This will give a 128x15x1000 size result.
If you have an earlier version of MATLAB that does not have pagemtimes, there are functions in the FEX that do the same thing such as mmx, mtimesx, and multiprod.
P.S. One of the problems with your original code is you were using the .* element-wise multiply operator instead of the * matrix multiply operator (without the dot). Hence the incompatible size error. It seems clear from the resulting size you wanted that the appropriate operater is the * matrix multiply.
  1 Comment
Shourya
Shourya on 9 Jul 2022
Edited: Shourya on 9 Jul 2022
@James Tursa Thank you very much. This was very helpful. I was unaware of pagemtimes and thank you for explaining the changes I should make in my code.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!