Matrix Indexing Being Slow

1 回表示 (過去 30 日間)
Groat
Groat 2015 年 3 月 4 日
コメント済み: Groat 2015 年 3 月 4 日
I'm running a function, let's say f(x), that depends on one variable (which may take any variable in the interval [0, 1]). This function gets called a lot of times (100,000+)
In my script, I can save a lot of calls of this function by storing f(0.5) for example, and then retrieving the stored value for f(0.5). I've tried to do this by creating a matrix A:
Row 1 = x
Row 2 = f(x)
However, my matrix indexing is taking a long time.
e.g. the below is taking 109 seconds with 11,000 calls
value = A(2, A(1, :) == 0.5);
Is there a more efficient way to do this? (Either the matrix indexing or the complete use of the function).
  1 件のコメント
Roger Stafford
Roger Stafford 2015 年 3 月 4 日
I think it is not the indexing that is slow. If you have accumulated a large number of values of the function in A, it is the scanning through all of these that takes the time. Writing A(1,:)==0.5 causes a scan of all different values which have been obtained.

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

回答 (1 件)

Adam
Adam 2015 年 3 月 4 日
Try using containers.Map.
You can set your values like 0.5 as keys and then use them to directly index into the map to retrieve the value
doc containers.Map
I haven't tried using it in a very dynamic way such as this or with such a large set of values so it may not be faster at all, but in theory a map which, by definition, has unique keys by which to look up a value should be what you want to do this. I have used maps for many things, but generally with < 50 elements in the map and those generally set at the start rather than being constantly dynamically added. Again, in theory, dynamically adding to a map should not cause large memory re-assignments and the like, but you would have to try it to see how effective it is.
  1 件のコメント
Groat
Groat 2015 年 3 月 4 日
Thank you for the suggestion Adam! I'd not heard of the containers.Map setup, but it's definitely quicker.

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by