Main Content

Map 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.

Map to Structure Array

The following example maps airline seat numbers to structures that contain ticket numbers and destinations. Start with the Map ticketMap, which maps ticket numbers to passengers:

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

Then create the following structure array, containing ticket numbers and destinations:

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 seats to 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:


ans = 

      ticketNum: 'B7398'
    destination: 'Granada'
       reserved: '30-Apr-2008'
         origin: 'JFK'

Using ticketMap and seatingMap together, you can find the name of the person who has reserved seat 15B:

ticket = seatingMap('15B').ticketNum;
passenger = ticketMap(ticket)

passenger =

Sarah Latham

Map to 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.

See Also

| | | | |

Related Topics