开发者

How to optimize norm calculation in Matlab?

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 开发者_如何学JAVAit 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 ?


  • 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));


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜