Alternative to num2str when looking up in containers.Map (performance)

13 views (last 30 days)
Hi,
I have implemented A* for x,y grid maps. I use two containers.Map to keep track of visited nodes and running cost, since containers.Map seemed nice to work with as similar to dictionaries.
My key for the containers.Map are the x,y coordinates of visited nodes. I have my nodes as a vector when I use them, i.e. startNode = [x y].
When I want to use them as a key for the containers.Map, I use num2str lige in the following
startNode = [1 1];
currentCost = containers.Map;
currentCost[num2str(startNode)] = 0;
It works really fine, except that I have num2str in my inner loop of the algorithm, and hence it can be called many many times e.g. 600.000-700.000 times. According to profiler num2str (and hence int2str) amounts to 50-75% of the overall processing time.
I have already optimized the code some, and was able to place some of the num2str calls outside the inner loop, which reduced the amount of calls by 60%, which is what amounts to the above mentioned 50-75%.
I am looking for some suggestions and ideas to what I could use, either instead of num2str that would have a better performance, and still be able to work with containers.Map, or perhaps a different approach, which could work just as well instead of containers.Map, but perhaps just use the node vector itself [x y], without converting it to a string? Note, I do the conversion because the key for containers.Map must be a string.
Best regards

Accepted Answer

Walter Roberson
Walter Roberson on 5 Apr 2016
currentCost[sprintf('%d %d', startNode)] = 0;
  2 Comments
Simon
Simon on 6 Apr 2016
Very good, that reduced the calculation time by ~40%.
As a small follow-up, what would be the best way to get the string back to a vector: '1 1' -> [1 1]

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!