Element wise multiplication multi dimensional

9 次查看(过去 30 天)
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