Matrix multiplication of 3d arrays

조회 수: 47 (최근 30일)
Riaz Patel
Riaz Patel 2018년 5월 16일
답변: michio 2020년 10월 12일
Hi
I have a 3d array of dimension 2*5000*150 and another array of dimension 5000*1*150. I would like to take each 2*5000 matrix in the first 3d array and multiply it with the corresponding 5000*1 matrix in the second 3d array.
I need to do this in as efficient a way as possible and without any additional functions that are not preinstalled on a standard matlab installation.

답변 (3개)

michio
michio 2020년 10월 12일

Ameer Hamza
Ameer Hamza 2018년 5월 16일
Just use for loop
result = zeros(2,1,150);
for i=1:150
result(:,:,i) = matrix1(:,:,i)*matrix2(:,:,i);
end
  댓글 수: 2
Riaz Patel
Riaz Patel 2018년 5월 16일
I need it to be extremely fast, the assignment I'm working on has a component for speed of the code.
Also these 3d arrays are already generated in a for loop. So I'm trying to avoid a nested loop.
Ameer Hamza
Ameer Hamza 2018년 5월 16일
The MATLAB syntax does not allow such mixing of element-wise and matrix multiplication between two matrices in a single command. Any other manipulation you will try to do will just add extra time or memory overhead. For example, you can make you code compact to just one line
result = cell2mat(cellfun(@(x,y) x*y, num2cell(x,[1 2]), num2cell(y,[1 2]), 'UniformOutput', false));
but this is very slower than for loop. MATLAB matrix operations are already very optimized so even creating a mex file is unlikely to help. for loop will be the fastest you can get in this case.

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


James Tursa
James Tursa 2018년 5월 16일
편집: James Tursa 2018년 5월 16일
Some options from the FEX:
MULTIPROD:
MTIMESX: (C-mex code requiring C compiler) needs updated build routine for later MATLAB versions
MMX: (C-mex code requiring C compiler)
And raw times code:
result = sum(bsxfun(@times,matrix1,reshape(matrix2,1,5000,150)),2);
or
result = sum(matrix1.*reshape(matrix2,1,5000,150),2); % later versions of MATLAB

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by