フィルターのクリア

How do I efficiently calculate a scalar distance with 3d geometry?

8 ビュー (過去 30 日間)
Henry
Henry 2013 年 7 月 29 日
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.
Any suggestions?
Thanks!

回答 (2 件)

Matt J
Matt J 2013 年 7 月 29 日
This might speed things up,
Haven't used it myself, though.
  2 件のコメント
Matt J
Matt J 2013 年 7 月 30 日
編集済み: Matt J 2013 年 7 月 30 日
It should also help (a little) if you don't compute x-x2 etc... twice. So in other words, you would first do
dx=x-x2;
dy=y-y2;
dz=z-z2;
and then
r2 = sqrt(dx.*dx +dy.*dy +dz.*dz);
or whatever...
Jan
Jan 2013 年 7 月 30 日
DNorm2 requires matrices as input and creating [dx, dy, dz] at first wastes too much time. So if the data could be organized as [500 x 3] matrix instead of three vectors, DNorm2 would be an option.

サインインしてコメントする。


Richard Brown
Richard Brown 2013 年 7 月 29 日
編集済み: Richard Brown 2013 年 7 月 29 日
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?

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by