Main Content

Create Map Object

A Map is an object of the Map class. It is defined within a MATLAB® package called containers. As with any class, you use its constructor function to create any new instances of it. You must include the package name when calling the constructor:

newMap = containers.Map(optional_keys_and_values)

Construct Empty Map Object

When you call the Map constructor with no input arguments, MATLAB constructs an empty Map object. When you do not end the command with a semicolon, MATLAB displays the following information about the object you have constructed:

newMap = containers.Map

newMap = 

  Map with properties:

        Count: 0
      KeyType: char
    ValueType: any

The properties of an empty Map object are set to their default values:

  • Count = 0

  • KeyType = 'char'

  • ValueType = 'any'

Once you construct the empty Map object, you can use the keys and values methods to populate it. For a summary of MATLAB functions you can use with a Map object, see Methods of Map Class

Construct Initialized Map Object

Most of the time, you will want to initialize the Map with at least some keys and values at the time you construct it. You can enter one or more sets of keys and values using the syntax shown here. The brace operators ({}) are not required if you enter only one key/value pair:

mapObj = containers.Map({key1, key2, ...}, {val1, val2, ...});

For those keys and values that are character vectors, be sure that you specify them enclosed within single quotation marks. For example, when constructing a Map that has character vectors as keys, use

mapObj = containers.Map(...
   {'keystr1', 'keystr2', ...}, {val1, val2, ...});

As an example of constructing an initialized Map object, create a new Map for the following key/value pairs taken from the monthly rainfall map shown earlier in this section.

k = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ...
  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Annual'};

v = {327.2, 368.2, 197.6, 178.4, 100.0,  69.9, ...
  32.3,  37.3,  19.0,  37.0,  73.2, 110.9, 1551.0};

rainfallMap = containers.Map(k, v)

rainfallMap = 

  Map with properties:

        Count: 13
      KeyType: char
    ValueType: double

The Count property is now set to the number of key/value pairs in the Map, 13, the KeyType is char, and the ValueType is double.

Combine Map Objects

You can combine Map objects vertically using concatenation. However, the result is not a vector of Maps, but rather a single Map object containing all key/value pairs of the contributing Maps. Horizontal vectors of Maps are not allowed. See Build Map with Concatenation, below.

See Also

| |

Related Topics