Modifying Keys and Values in the Map

    Note:   Keep in mind that if you have more than one handle to a Map, modifying the handle also makes changes to the original Map. See Modifying a Copy of the Map, below.

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');

Start with the Map ticketMap :

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

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

remove(ticketMap, 'NZ1452');

ans = 

    'James Enright'    '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:


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:


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 the ticketMap Map. Write to this copy, and notice that the change is applied to the original Map object itself:

copiedMap = ticketMap;

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

ans =

unidentified person

Clean up:

remove(ticketMap, 'AZ12345');
clear copiedMap;
Was this topic helpful?