Matrix Indexing Being Slow
1 次查看(过去 30 天)
显示 更早的评论
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
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
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!