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

49 次查看(过去 30 天)
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';

采纳的回答

Torsten
Torsten 2022-7-8
编辑:Torsten 2022-7-8
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

更多回答(2 个)

Voss
Voss 2022-7-8
% 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

James Tursa
James Tursa 2022-7-8
编辑:James Tursa 2022-7-8
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 个评论
Shourya
Shourya 2022-7-9
编辑:Shourya 2022-7-9
@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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by