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

조회 수: 50 (최근 30일)
Shourya
Shourya 2022년 7월 8일
댓글: Voss 2022년 7월 9일
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
  댓글 수: 2
Shourya
Shourya 2022년 7월 9일
편집: Shourya 2022년 7월 9일
@Voss Thank you very much. I tried this code too and it workes!
Voss
Voss 2022년 7월 9일
You're welcome!

댓글을 달려면 로그인하십시오.


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