Pagewise multiplication along a dimension without using a for loop?

조회 수: 1 (최근 30일)
Nathan Zechar
Nathan Zechar 2025년 3월 10일
댓글: Matt J 2025년 3월 16일
Hello, is there a way code pagewise multiplication along a single dimension of a matrix without using a for loop?
In the example below, I have a single 4D matrix where I use pagewise multiplication along its 4th dimension in a for loop to achieve a 3D matrix.
Is there a way to remove the for loop from this?
X = randi([1 10],2,2,10,5);
Y = pagemtimes(X(:,:,:,1),X(:,:,:,2));
for i = 3:length(X(1,1,1,:))
Y = pagemtimes(Y,X(:,:,:,i));
end

답변 (2개)

Matt J
Matt J 2025년 3월 10일
편집: Matt J 2025년 3월 10일
No, but looking at your code, I would guess that the speed is being encumbered much more by the operation length(X(1,1,1,:)) than by anything else. You should instead do,
for i = 3:size(X,4)
Y = pagemtimes(Y,X(:,:,:,i));
end
You would need an incredibly large size(X,4) relative to the other dimensions for the for-loop itself to be a significant bottleneck. If that's the case though, you might be able to benefit from a parfor loop, as demonstrated below,
X = randi([1 10],2,2,10,1e6);
Y = pagemtimes(X(:,:,:,1),X(:,:,:,2));
tic;
parfor i = 3:size(X,4)
Y = pagemtimes(Y,X(:,:,:,i));
end
toc
Elapsed time is 0.784269 seconds.
tic;
for i = 3:size(X,4)
Y = pagemtimes(Y,X(:,:,:,i));
end
toc
Elapsed time is 2.254356 seconds.
  댓글 수: 4
Nathan Zechar
Nathan Zechar 2025년 3월 16일
X could range from 5 to maybe as high as 100 for my application,
The output gives an analytical solution used to minimize data to find an unknown. So process has to be called several times to generate central difference derivatives within a loop, and that process repeats until convergence critera has been reached. It adds up. But aside from that, I was just curious if something like this could be done within matlab.
Matt J
Matt J 2025년 3월 16일
The Optimization Toolbox solvers let yoy parallelize central difference computations in their iterative loops. That might be somethign to consider.

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


Matt J
Matt J 2025년 3월 13일
편집: Matt J 2025년 3월 13일
If you can build X in cell array form, instead of 4D form, you can save some time as well:
X = randi([1 10],2,2,10,5);
Xc = num2cell( X , 1:3 );
timeit(@()version1(X))*1e6
ans = 18.1973
timeit(@()version2(Xc))*1e6
ans = 6.8640
function version1(X)
Y = pagemtimes(X(:,:,:,1),X(:,:,:,2));
for i = 3:size(X,4)
Y = pagemtimes(Y,X(:,:,:,i));
end
end
function version2(Xc)
Y = pagemtimes(Xc{1},Xc{2});
for i = 3:numel(Xc)
Y = pagemtimes(Y,Xc{i});
end
end

카테고리

Help CenterFile Exchange에서 Arithmetic Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by