Speeding Up Logical Operations

3 ビュー (過去 30 日間)
Amit
Amit 2014 年 12 月 9 日
Hi Guys,
I am trying to uses the function below
function coords = distancePerBound(coords,L)
hL = L/2;
coords(coords > hL) = coords(coords > hL) - L;
coords(coords < -hL) = coords(coords < -hL) + L;
end
where coords is a 3xn (where n is ~100,000). In the function that uses it, this function gets called many times and is a bottle neck in speed. Is there any thing I can do to improve this?
On a side note, I know that for a vector 'x', x.*x is faster than x.^2. Is there any speeding possibility for 1./x as well? Thank you.

採用された回答

Matt J
Matt J 2014 年 12 月 9 日
function coords = distancePerBound(coords,L)
hL = L/2;
idx=coords > hL;
coords(idx) = coords(idx) - L;
idx=coords < -hL;
coords(idx) = coords(idx) + L;
end
  7 件のコメント
Sean de Wolski
Sean de Wolski 2014 年 12 月 9 日
Ahh! minus signs matter!
Carlos Adrian Vargas Aguilera
Carlos Adrian Vargas Aguilera 2020 年 4 月 11 日
Well, after all you already get important info with >hL. Maybe
function coords = distancePerBound(coords,L)
hL = L/2;
idx = coords > hL;
coords(idx) = coords(idx) - L;
idx(~idx) = coords(~idx) >= -hL;
coords(~idx) = coords(~idx) + L;
end

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

その他の回答 (1 件)

Adam
Adam 2014 年 12 月 9 日
編集済み: Adam 2014 年 12 月 9 日
What does the profiler say about the speed of this?
Is it the function that is slow or the number of times you call it?
Within the function it is vectorised, but calling it many times lessens that effect because the many calls are not vectorised together.
Can you not concatenate the data input to the many calls to make just a single call?
Again though this comes down to where exactly the profiler is pointing to as being slow.
As an aside there are various alternatives that can be tried. If it were me and this function were found to be slow I would create a quick test script containing as many of those options as I can think of and see which is fastest because it is often hard to tell without simply trying and timing the different implementations.
  8 件のコメント
Adam
Adam 2014 年 12 月 9 日
In that case it would come down to what i said earlier I guess. Create a simple test program with different implementations of that one function, make sure they all give the same answer, time them all and see if any is faster than the current.
I don't personally see much that I would be able to say would be a lot faster than you have, but optimised functions in Matlab can be strange sometimes so only the implementation and timing of the alternatives will tell for sure.
Amit
Amit 2014 年 12 月 9 日
Very true Adam. Actually that was what I was doing :P when I ran out of ideas, I thought to ask more experienced programmers here !!

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

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by