3

Is there a bidirectional map data structure in matlab that is more efficient than using containers.Map's keys and values in an opposite direction? Also what is the most efficient way to use ordinary maps for this purpose?

Dandelion
  • 744
  • 2
  • 13
  • 34
  • What data do you want to store? – knedlsepp Mar 01 '15 at 12:50
  • Mapping between integers – Dandelion Mar 01 '15 at 12:55
  • 1
    Please add example data to your question. Also tell us how often you are going to insert new data or delete data into your bidirectional map. Different solutions will show different efficiency for different use cases. For positive integers you could try [`sparse`](http://www.mathworks.com/help/matlab/ref/sparse.html). – knedlsepp Mar 01 '15 at 12:57
  • This is a general question and bidirectional maps are well known structures. – Dandelion Mar 01 '15 at 13:02
  • If you want the most general solution, you won't get the most efficient one for your use case. – knedlsepp Mar 01 '15 at 13:03

1 Answers1

4

The containers.Map class does not natively support bidirectional mapping (as of R2014b). The methods supported are listed in doc containers.Map:

  • isKey: Determine if containers.Map object contains key
  • keys: Identify keys of containers.Map object
  • length: Length of containers.Map object
  • remove: Remove key-value pairs from containers.Map object
  • size: Size of containers.Map object
  • values: Identify values in containers.Map object

You could either implement this functionality yourself, by building

inverse = containers.Map(original.values, original.keys)

Or use the Map2-class provided by Mikko Leppänen on the File Exchange:

[...] Also a bidirectional use of key-value pairs is supported (like Boost.Bimap library).


If your key-value pairs are positive integers and you rarely change the map, you could use sparse, which should be quite efficient.

map = sparse(keys, 1, values);
inverseMap = sparse(nonzeros(map), 1, find(map))
knedlsepp
  • 6,065
  • 3
  • 20
  • 41