Matrix Indexing Being Slow

10 views (last 30 days)
Groat
Groat on 4 Mar 2015
Commented: Groat on 4 Mar 2015
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 Comment
Roger Stafford
Roger Stafford on 4 Mar 2015
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.

Sign in to comment.

Answers (1)

Adam
Adam on 4 Mar 2015
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 Comment
Groat
Groat on 4 Mar 2015
Thank you for the suggestion Adam! I'd not heard of the containers.Map setup, but it's definitely quicker.

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!