MATLAB: [HELP] Vector loops :'(

matlab for loops vectorize

Anybody knows how can i optimize this? Thanks <3!
function filter()
r=[cos(c) -sin(c);
sin(c) cos(c)];
for i = 1 : n2
for j = 1 : n1
h(i,j) = magic(r(1),std)*magic(r(2),std);
end
end
function y = magic(r,s)
y = exp(-r^2));

Best Answer

You have set std1 and std2 to equal values. Provided you do that, the result in 'h' is independent of the value 'c' and can be vectorized as:
n1 = 10;
n2 = 3;
s = 2
h = exp(-(((1-n2)/2:(n2-1)/2)').^2/(2*s^2))*...
exp(-(((1-n1)/2:(n1-1)/2)).^2/(2*s^2))/s^2/(2*pi);
The code can also be vectorized with unequal values of std1 and std2, but is somewhat more complicated. Do you wish to see that?
Related Question