Search code examples
matlabdictionarybidirectional

Is there a bidirectional map in matlab?


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?


Solution

  • 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))