I am writing a Matlab application that computes some sort of matrix. I'm trying to replace the for loops in my program with vector-based calculations, however, I'm stuck.
So far, I have figured that this simple sample part of code:
kernel = zeros(5,5,5);
offset = 3;
sig=1;
for x=-2:2
for y=-2:2
for z=-2:2
IN = x.^2/(sig^2) + y.^2/(sig^2) + z.^2/(sig^2);
kernel(offset+x, offset+y, offset+z) = exp(-IN/2);
end
end
end
can be replaced with such a construction:
[x,y,z] = ndgrid(-2:2,-2:2,-2:2);
IN = x.^2/(sig^2) + y.^2/(sig^2) + z.^2/(sig^2);
kernel = exp(-IN/2);
and give the same results. But what if I need to make some small alteration:
kernel = zeros(5,5,5);
offset = 3;
sig=1;
%sample 3x3 matrix
R=magic(3)/10;
for x=-2:2
for y=-2:2
for z=-2:2
% calculation of new x, y, z
point = [x,y,z]*R;
IN = (point(1)^2 )/(sig^2) + (point(2)^2)/(sig^2) + (point(3)^2)/(sig^2);
kernel(offset+x, offset+y, offset+z) = exp(-IN/2);
end
end
end
How can I speed up this construction? Can it be easily vectorized? I'm quite new to Matlab, so I would appreciate any help. Thanks a lot!