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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by