Element wise multiplication multi dimensional

13 Ansichten (letzte 30 Tage)
Dylan Marques
Dylan Marques am 21 Mär. 2017
Bearbeitet: Dylan Marques am 21 Mär. 2017
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

Akzeptierte Antwort

Jan
Jan am 21 Mär. 2017
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 Kommentar
Dylan Marques
Dylan Marques am 21 Mär. 2017
Bearbeitet: Dylan Marques am 21 Mär. 2017
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!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Mathematics and Optimization finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by