Multiplication of matrix and first dimension of a 3-D array without for loops

조회 수: 1 (최근 30일)
Valentina Baccetti
Valentina Baccetti 2023년 1월 13일
답변: Matt J 2023년 1월 13일
Hi,
I'm fairly new to Matlab but I was wondering if there is a way to multiply a 2-D matrix by the first dimension of a 3-D array without using for loops, and obtain another 3-D array.
The matrix, let's call it A, would be something like A(n,n), while the 3-D would be something like B(n,l,k). What I would like to do is somehow multiple A(n,n)*B(n,l,k) for every value of l and k, without going through two for loops.
Example below
A = rand(4,4);
B = rand(4,10,5);
for i = 1:10
for j = 1:5
C(:,i,j) = A(:,:)*B(:,i,j);
end
end
Thanks
  댓글 수: 1
Rik
Rik 2023년 1월 13일
Why exactly do you want to remove the loop? And are you aware you're doing a matrix multiplication instead of an element-wise multiplication?

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

답변 (2개)

Bruno Luong
Bruno Luong 2023년 1월 13일
편집: Bruno Luong 2023년 1월 13일
A = rand(4,4);
B = rand(4,10,5);
% orginal code
for i = 1:10
for j = 1:5
C(:,i,j) = A(:,:)*B(:,i,j);
end
end
% one loop code
Coneloop = zeros(size(A,1),size(B,2),size(B,3));
for j = 1:size(B,3)
Coneloop(:,:,j) = A*B(:,:,j);
end
% no loop code
Cnoloop = pagemtimes(A,B);
% Check matching
norm(Coneloop(:)-C(:),'Inf')
ans = 4.4409e-16
norm(Cnoloop(:)-C(:),'Inf')
ans = 4.4409e-16
norm(Cnoloop(:)-Coneloop(:),'Inf')
ans = 0

Matt J
Matt J 2023년 1월 13일
C=reshape( A*B(:,:) , size(B));

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by