How to multiply a 3d array with a 2d matrix?
조회 수: 52 (최근 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';
댓글 수: 0
채택된 답변
추가 답변 (2개)
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
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!