Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

Map Containers

Overview of the Map Data Structure

A Map is a type of fast key lookup data structure that offers a flexible means of indexing into its individual elements. Unlike most array data structures in the MATLAB software that only allow access to the elements by means of integer indices, indices for a Map can be nearly any scalar numeric value or a character string.

Indices into the elements of a Map are called keys. These keys, along with the data values associated with them, are stored within the Map. Each entry of a Map contains exactly one unique key and its corresponding value. Indexing into the Map of rainfall statistics shown below with a string representing the month of August yields the value internally associated with that month, 37.3.

Mean monthly rainfall statistics (mm)

Keys are not restricted to integers as they are with other arrays. Specifically, a key may be any of the following types:

The values stored in a Map can be of any type. This includes arrays of numeric values, structures, cells, strings, objects, or other Maps.

Description of the Map Class

A Map is actually an object, or instance, of a MATLAB class called Map. It is also a handle object and, as such, it behaves like any other MATLAB handle object. This section gives a brief overview of the Map class. For more details, see the function reference pages for the Map constructor or for any method of the class.

Properties of the Map Class

All objects of the Map class have three properties. You cannot write directly to any of these properties; you can change them only by means of the methods of the Map class.

PropertyDescriptionDefault
CountUnsigned 64-bit integer that represents the total number of key/value pairs contained in the Map object.0
KeyTypeString that indicates the type of all keys contained in the Map object. KeyType can be any of the following: double, single, char, and signed or unsigned 32-bit or 64-bit integer. If you attempt to add keys of an unsupported type, int8 for example, MATLAB makes them double.char
ValueTypeString that indicates the type of values contained in the Map object. If the values in a Map are all scalar numbers of the same type, ValueType is set to that type. If the values are all character arrays, ValueType is 'char'. Otherwise, ValueType is 'any'.any

To examine one of these properties, follow the name of the Map object with a dot and then the property name. For example, to see what type of keys are used in Map mapObj, use

mapObj.KeyType

A Map is a handle object. As such, if you make a copy of the object, MATLAB does not create a new Map; it creates a new handle for the existing Map that you specify. If you alter the Map's contents in reference to this new handle, MATLAB applies the changes you make to the original Map as well. You can, however, delete the new handle without affecting the original Map.

Methods of the Map Class

The Map class implements the following methods. Their use is explained in the later sections of this documentation and also in the function reference pages.

MethodDescription
isKeyCheck if Map contains specified key
keysNames of all keys in Map
lengthLength of Map
removeRemove key and its value from Map
sizeDimensions of Map
valuesValues contained in Map

Creating a 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)

Constructing an 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 = 
   containers.Map handle
   package: containers
   properties:
           Count: 0
         KeyType: 'char'
       ValueType: 'any'
   lists of Methods, Events, Superclasses

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

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 the Map Class

Constructing An 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 strings, be sure that you specify them enclosed within single quotation marks. For example, when constructing a Map that has character string 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 = 
  containers.Map handle
  Package: containers

  Properties:
        Count: 13
      KeyType: 'char'
    ValueType: 'double'
  Methods, Events, Superclasses

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.

Combining 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 Building a Map with Concatenation, below.

Examining the Contents of the Map

Each entry in a Map consists of two parts: a unique key and its corresponding value. To find all the keys in a Map, use the keys method. To find all of the values, use the values method.

Create a new Map called tickets that maps airline ticket numbers to the holders of those tickets. Construct the Map with four key/value pairs:

ticketMap = containers.Map(...
    {'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
    {'James Enright', 'Carl Haynes', 'Sarah Latham', ...
     'Bradley Reid'});

Use the keys method to display all keys in the Map. MATLAB lists keys of type char in alphabetical order, and keys of any numeric type in numerical order:

keys(ticketMap)
ans = 
   '2R175'  'A479GY'  'B7398'  'NZ1452'

Next, display the values that are associated with those keys in the Map. The order of the values is determined by the order of the keys associated with them.

This table shows the keys listed in alphabetical order:

keysvalues
2R175James Enright
A479GYSarah Latham
B7398Carl Haynes
NZ1452Bradley Reid

The values method uses the same ordering of values:

values(ticketMap)
ans = 
  'James Enright'  'Sarah Latham'  'Carl Haynes'  'Bradley Reid'

Reading and Writing Using a Key Index

When reading from the Map, use the same keys that you have defined and associated with particular values. Writing new entries to the Map requires that you supply the values to store with a key for each one .

Reading From the Map

After you have constructed and populated your Map, you can begin to use it to store and retrieve data. You use a Map in the same manner that you would an array, except that you are not restricted to using integer indices. The general syntax for looking up a value (valueN) for a given key (keyN) is shown here. If the key is a character string, enclose it in single quotation marks:

valueN = mapObj(keyN);

You can find any single value by indexing into the map with the appropriate key:

passenger = ticketMap('2R175')
passenger =
   James Enright

Find the person who holds ticket A479GY:

sprintf('   Would passenger %s please come to the desk?\n', ...
    ticketMap('A479GY'))
ans =
    Would passenger Sarah Latham please come to the desk?

To access the values of multiple keys, use the values method, specifying the keys in a cell array:

values(ticketMap, {'2R175', 'B7398'})
ans = 
    'James Enright'    'Carl Haynes'

You cannot use the colon operator to access a range of keys as you can with other MATLAB classes. For example, the following statement throws an error:

ticketMap('2R175':'B7398')

Adding Key/Value Pairs

Unlike other array types, each entry in a Map consists of two items: the value and its key. When you write a new value to a Map, you must supply its key as well. This key must be consistent in type with any other keys in the Map.

Use the following syntax to insert additional elements into a Map:

existingMapObj(newKeyName) = newValue;

Add two more entries to the ticketMap used in the above examples, Verify that the Map now has five key/value pairs:

ticketMap('947F4') = 'Susan Spera';
ticketMap('417R93') = 'Patricia Hughes';

ticketMap.Count
ans =
     6

List all of the keys and values in Map ticketMap:

keys(ticketMap),  values(ticketMap)
ans = 
   '2R175'   '417R93'   '947F4'   'A479GY'   'B7398'   'NZ1452'
ans = 
  Columns 1 through 3
    'James Enright'   'Patricia Hughes'   'Susan Spera'
  Columns 4 through 6
    'Sarah Latham'   'Carl Haynes'   'Bradley Reid'

Building a Map with Concatenation

You can add key/value pairs to a Map in groups using concatenation. The concatenation of Map objects is different from other classes. Instead of building a vector of s, MATLAB returns a single Map containing the key/value pairs from each of the contributing Map objects.

Rules for the concatenation of Map objects are:

Modifying Keys and Values in the Map

In addition to reading and writing the contents of a Map, you can also delete key/value pairs and modify any of its values or keys.

Removing Keys and Values from the Map

Use the remove method to delete any entries from a Map. When calling this method, specify the Map object name and the key name to remove. MATLAB deletes the key and its associated value from the Map.

The syntax for the remove method is

remove('mapName', 'keyname');

Remove one entry (the specified key and its value) from the Map object:

remove(ticketMap, 'NZ1452');
values(ticketMap)
ans = 
  Columns 1 through 3
    'James Enright'    'Patricia Hughes'    'Susan Spera'
  Columns 4 through 5
    'Sarah Latham'    'Carl Haynes'

Modifying Values

You can modify any value in a Map simply by overwriting the current value. The passenger holding ticket A479GY is identified as Sarah Latham:

ticketMap('A479GY')
ans =
    Sarah Latham

Change the passenger's first name to Anna Latham by overwriting the original value for the A479GY key:

ticketMap('A479GY') = 'Anna Latham';

Verify the change:

ticketMap('A479GY')
ans =
    'Anna Latham';

Modifying Keys

To modify an existing key while keeping the value the same, first remove both the key and its value from the Map. Then create a new entry, this time with the corrected key name.

Modify the ticket number belonging to passenger James Enright:

remove(ticketMap, '2R175');
ticketMap('2S185') = 'James Enright';

k = keys(ticketMap);  v = values(ticketMap);
str1 = '   ''%s'' has been assigned a new\n';
str2 = '    ticket number: %s.\n';

fprintf(str1, v{1})
fprintf(str2, k{1})

 'James Enright' has been assigned a new
    ticket number: 2S185.

Modifying a Copy of the Map

Because ticketMap is a handle object, you need to be careful when making copies of the Map. Keep in mind that by copying a Map object, you are really just creating another handle to the same object. Any changes you make to this handle are also applied to the original Map.

Make a copy of Map ticketMap. Write to this copy, and notice that the change is applied to the original Map object itself:

copiedMap = ticketMap;

copiedMap('AZ12345') = 'unidentified person';
ticketMap('AZ12345')
ans =
    unidentified person

Clean up:

remove(ticketMap, 'AZ12345');
clear copiedMap;

Mapping to Different Value Types

It is fairly common to store other classes, such as structures or cell arrays, in a Map structure. However, Maps are most memory efficient when the data stored in them belongs to one of the basic MATLAB types such as double, char, integers, and logicals.

Mapping to a Structure Array

The following example maps airline seat numbers to structures that contain information on who occupies the seat. To start out, create the following structure array:

s1.ticketNum = '2S185'; s1.destination = 'Barbados';
s1.reserved = '06-May-2008'; s1.origin = 'La Guardia';
s2.ticketNum = '947F4'; s2.destination = 'St. John';
s2.reserved = '14-Apr-2008'; s2.origin = 'Oakland';
s3.ticketNum = 'A479GY'; s3.destination = 'St. Lucia';
s3.reserved = '28-Mar-2008'; s3.origin = 'JFK';
s4.ticketNum = 'B7398'; s4.destination = 'Granada';
s4.reserved = '30-Apr-2008'; s4.origin = 'JFK';
s5.ticketNum = 'NZ1452'; s5.destination = 'Aruba';
s5.reserved = '01-May-2008'; s5.origin = 'Denver';

Map five of the seats to one of these structures:

seatingMap = containers.Map( ...
    {'23F', '15C', '15B', '09C', '12D'}, ...
    {s5, s1, s3, s4, s2});

Using this Map object, find information about the passenger, who has reserved seat 09C:

seatingMap('09C')
ans = 
      ticketNum: 'B7398'
    destination: 'Granada'
       reserved: '30-Apr-2008'
         origin: 'JFK'
seatingMap('15B').ticketNum
ans =
    A479GY

Using two Maps together, you can find out the name of the person who has reserved the seat:

passenger = ticketMap(seatingMap('15B').ticketNum)
passenger =
   Anna Latham

Mapping to a Cell Array

As with structures, you can also map to a cell array in a Map object. Continuing with the airline example of the previous sections, some of the passengers on the flight have "frequent flyer" accounts with the airline. Map the names of these passengers to records of the number of miles they have used and the number of miles they still have available:

accountMap = containers.Map( ...
    {'Susan Spera','Carl Haynes','Anna Latham'}, ...
    {{247.5, 56.1}, {0, 1342.9}, {24.6, 314.7}});

Use the Map to retrieve account information on the passengers:

name = 'Carl Haynes';
acct = accountMap(name);

fprintf('%s has used %.1f miles on his/her account,\n', ...
    name, acct{1})
fprintf('  and has %.1f miles remaining.\n', acct{2})

Carl Haynes has used 0.0 miles on his/her account,
  and has 1342.9 miles remaining.
  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS