Element wise multiplication multi dimensional

조회 수: 11 (최근 30일)
Dylan Marques
Dylan Marques 2017년 3월 21일
편집: Dylan Marques 2017년 3월 21일
Hello,
I'm currently making a numerical algorithms which require multi dimensional matrix (5D).
To speed up the algorithm I vectorized the program but this origins that I run out of memory very easily.
Most of my code has statement as:
[thetaIM, phiIM,thetaRM, phiRM] = ndgrid(linspace(thetaIAux(1),thetaIAux(3),thetaIAux(2)),...
linspace(phiIAux(1),phiIAux(3),phiIAux(2)),linspace(thetaRAux(1),thetaRAux(3),thetaRAux(2)),...
linspace(phiRAux(1),phiRAux(3),phiRAux(2)));
A = ones(thetaIAux(2),phiIAux(2),thetaRAux(2),phiRAux(2),3);
B = repmat(thetaRM,[1,1,1,1,3]);
C = A .* B
This approach really speed up the program but it uses a lot of unnecessary memory. So, there are no way to make a vectorize code that does the following:
[thetaIM, phiIM,thetaRM, phiRM] = ndgrid(linspace(thetaIAux(1),thetaIAux(3),thetaIAux(2)),...
linspace(phiIAux(1),phiIAux(3),phiIAux(2)),linspace(thetaRAux(1),thetaRAux(3),thetaRAux(2)),...
linspace(phiRAux(1),phiRAux(3),phiRAux(2)));
A = ones(thetaIAux(2),phiIAux(2),thetaRAux(2),phiRAux(2),3);
C = zeros(thetaIAux(2),phiIAux(2),thetaRAux(2),phiRAux(2),3);
B = thetaRM;
for i=1:3
C(:,:,:,:,i) = A(:,:,:,:,i).*B
end
Or any other approach to do the same?
Many thanks Dylan Marques

채택된 답변

Jan
Jan 2017년 3월 21일
I do not see why you create the ndgrid with 4 outputs, when only thetaRM is used. In Matlab >= R2016b you can apply the elementwise multiplication on vectors in different dimensions directly:
a = linspace(thetaIAux(1),thetaIAux(3),thetaIAux(2));
b = linspace(phiIAux(1),phiIAux(3),phiIAux(2));
c = linspace(thetaRAux(1),thetaRAux(3),thetaRAux(2));
d = linspace(phiRAux(1),phiRAux(3),phiRAux(2));
B = reshape(a, [thetaIAux(2), 1, 1, 1]) .* ...
reshape(b, [1, phiIAux(2), 1, 1]) .* ...
reshape(c, [1, 1, thetaRAux(2), 1]) .* ...
reshape(d, [1, 1, 1, phiRAux(2)]);
You can skip the trailing 1's in reshape, but I've included them for clarity here. Finally:
C = repmat(B, [1, 1, 1, 1, 3]);
Or if the ones() was to create dummy data only for the forum, another elementwise multiplication can solve this.
If you use Matlab version < 2016b, bsxfun helps:
B = bsxfun(@times, reshape(a, [thetaIAux(2), 1, 1, 1]), ... etc
  댓글 수: 1
Dylan Marques
Dylan Marques 2017년 3월 21일
편집: Dylan Marques 2017년 3월 21일
Hello Jam,
In the part of the example that I show it is not required the 4D matrix but I needed it later.
But now with the bsxfun I wont required anymore the ndgrid which will allow me to economize a lot of memory.
Thanks for the help!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics and Optimization에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by