Element wise multiplication multi dimensional

9 visualizaciones (últimos 30 días)
Dylan Marques
Dylan Marques el 21 de Mzo. de 2017
Editada: Dylan Marques el 21 de Mzo. de 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

Respuesta aceptada

Jan
Jan el 21 de Mzo. de 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 comentario
Dylan Marques
Dylan Marques el 21 de Mzo. de 2017
Editada: Dylan Marques el 21 de Mzo. de 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!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Mathematics and Optimization en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by