views:

63

answers:

3

I had like to optimize the following Matlab code :

x = linspace(-5,5,100);
y = linspace(-5,5,100);
z = linspace(-5,5,100);
[xp,yp,zp] = meshgrid(x,y,z);

norm = sqrt(xp.^2+yp.^2+zp.^2);

I improved it a little using realsqrt :

norm_0 = sqrt(xp.^2+yp.^2+zp.^2) 10.106 s 37.0%
norm_1 = realsqrt(xp.^2+yp.^2+zp.^2) 10.100 s 35.0%

Any other ideas ?

A: 

Just use standard norm function, it is probably implemented using C, which makes it faster that doing anything in many steps in Matlab.

Marcus Johansson
Sorry in this particular case, I don't see how to take element-wise the norm of the vector [xp,yp,zp]. Any idea ?
ths1104
`norm([xp yp zp])`.
Oli Charlesworth
@Marcus Johansson, @Oli Charlesworth: `norm` won't work here. If you call it with an array, `norm` returns a matrix norm, not a list of vector norms.
Jonas
A: 

I doubt that this individual line can be optimized very much. However, for it to take 10 seconds, I guess that it is called inside a loop, which suggests that there is potential for optimizing the entire function.

Also, you may be trying to create a circle somewhere later by thresholding the radius. Instead of taking the square root, you could instead threshold against the square of the radius, and make the code thus faster.

Jonas
+1  A: 
  • sqrt() is expensive, so make sure you really need it, or - as Jonas pointed out - if you could instead threshold against the square of the radius

  • depending on your data, use the knowledge about the symmetry of the norm to reduce the number of sqrt calculations

  • precalculate the squares before generating the meshgrid

something like (untested):

x = linspace(-5, 5, 100);
y = linspace(-5, 5, 100);
z = linspace(-5, 5, 100);
[xp2, yp2, zp2] = meshgrid(x(1:end/2).^2, y(1:end/2).^2, z(1:end/2).^2);
norm_quadrant = sqrt(xp2 + yp2 + zp2);
norm_temp1 = cat(1, norm_quadrant, flipdim(norm_quadrant, 1));
norm_temp2 = cat(2, norm_temp1, flipdim(norm_temp1, 2));
norm_complete = cat(3, norm_temp2, flipdim(norm_temp2, 3));
groovingandi
@Jonas: It could work, especially as I am in cylindrical geometry.
ths1104
@groovingandi: As soon as I have the time to test this, I will. I will let you know. Thanks for the hints.
ths1104