This is how to make the three-loop version analogous to the meshgrid version
N = 300;
x = linspace(1,10,N);
y = linspace(1,10,N);
z = linspace(1,10,N);
s = 1;
t = 1;
M = rand(N,N,N);
tic
[a,b,c] = meshgrid(x,y,z);
result = (((c*s - b*t).^2)./(a.^2 + b.^2 + c.^2)).*M;
toc
tic
result2 = zeros(length(x), length(y), length(z));
for iz = 1:length(x)
for jx = 1:length(y)
for ky = 1:length(z)
result2(iz,jx,ky) = M(iz,jx,ky)*(((z(iz)*s - y(ky)*t).^2)./(x(jx)^2 + y(ky)^2 + z(iz).^2));
end
end
end
toc
norm(result(:)-result2(:))./norm(result(:))
However I don't see how you can avoid running out of memory: meshgrid is creating a N*N*N (with my notation) matrix, if it runs out of memory, also the preallocation of the result matrix will
result2 = zeros(length(x), length(y), length(z));
It is however true that in the second version you only have 2 matrices with dimensions N*N*N (M and result2) whereas in the first case you have 5 (a, b, c, M, result).
Note that according to my tests, the meshgrid version with vectorization is always faster than the version with three loops
1 Comment
Direct link to this comment
https://la.mathworks.com/matlabcentral/answers/546329-memory-efficient-alternative-for-meshgrid#comment_893231
Direct link to this comment
https://la.mathworks.com/matlabcentral/answers/546329-memory-efficient-alternative-for-meshgrid#comment_893231
Sign in to comment.