How do I efficiently calculate a scalar distance with 3d geometry?
26 views (last 30 days)
I have a piece of code that is called many times (~5e5) during a time stepping solution. Having run profiler, the following line is slowing everything down:
r2 = sqrt((x-x2).*(x-x2)+(y-y2).*(y-y2)+(z-z2).*(z-z2));
Where x, y, z are (500, 1) and x2, y2, z2 are scalars.
Richard Brown on 29 Jul 2013
Edited: Richard Brown on 29 Jul 2013
You should use hypot. It also has better numerical stability.
edit sorry, you're in 3D. That obviously won't work. You can use hypot as
r = hypot((x-x2) + 1i*(y-y2), z - z2);
This may be slower than what you currently have though. If you use (x - x2).^2 instead of (x - x2) .* (x - x2) you'll probably get a small performance boost. Can you avoid calculating the square root and work with squared distance instead?