Element wise multiplication multi dimensional
9 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Jan
on 21 Mar 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
More Answers (0)
See Also
Categories
Find more on Mathematics and Optimization in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!