MATLAB: How to vectorize this function with nested FOR loop

for loopfunctionplotvectorvectorization

The function is:
x = -10:10;
y = -5:5;
for j = 1:21
for i = 1:11
f(i) = - 20 * exp( - 0.2 * sqrt( ( 1/2 ) * sum( x(j)^2 + y(i)^2 ) ) );
end
z(j,:) = f;
end
Thanks!

Best Answer

% MATLAB >= R2016b
z = - 20 * exp( - 0.2 * sqrt( .5 * sum( x(:).^2 + y(:)'.^2 ) ) );
% MATLAB <= R2016a
[xx,yy] = ndgrid(x,y);
z = - 20 * exp( - 0.2 * sqrt( .5 * sum( xx.^2 + yy.^2 ) ) );