Vectorising a for loop that creates a 2-D surface for each point in a Domain
1 view (last 30 days)
Show older comments
Hi, I'm having a bit of difficulty optimising the following piece of code:
x = [-2:0.1:2]
y = x'
for i = 1:numel(x)
for j = 1:numel(x)
z(:,:,i,j) = 0.5*exp(-(((x(i)-x).^2)/0.2 + ((x(j)-y).^2)/0.2));
end
end
The code creates a surface at each point in a domain. I would like know whether it would be possible to vectorise this for loop since I would like to be able to do this for larger domains and hence need a faster way of doing this. Any help is much appreciated.
1 Comment
per isakson
on 30 Jul 2018
"for larger domains and hence need a faster " How large and how fast do you aim at?
Accepted Answer
per isakson
on 30 Jul 2018
Edited: per isakson
on 30 Jul 2018
Matlab loops are faster than their reputation. I believe it's difficult to significantly outperform this function
function z = cssm( )
x = -2:0.05:2;
y = x';
n = numel(x);
z = nan(n,n,n,n); % pre-allocation is a must!
%
f = nan(n,n);
for kk = 1:n
f(kk,:) = exp(-((x(kk)-x).^2)/0.2);
end
for ii = 1:n
for jj = 1:n
z(:,:,ii,jj) = 0.5 .* f(ii,:) .* f(jj,:)';
end
end
end
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!