Modify 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.
Modify Copy of 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';
ticketMap('AZ12345')
ans =
unidentified person
Clean up:
remove(ticketMap, 'AZ12345');
clear copiedMap;
See Also
keys | isKey | values | containers.Map | remove | length | size
Related Examples
•
“Create Map Object” on page 14-6
•
“Examine Contents of Map” on page 14-8
•
“Read and Write Using Key Index” on page 14-9
•
“Map to Different Value Types” on page 14-15
14 Map Containers
14-14
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.
Modify Copy of 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';
ticketMap('AZ12345')
ans =
unidentified person
Clean up:
remove(ticketMap, 'AZ12345');
clear copiedMap;
See Also
keys | isKey | values | containers.Map | remove | length | size
Related Examples
•
“Create Map Object” on page 14-6
•
“Examine Contents of Map” on page 14-8
•
“Read and Write Using Key Index” on page 14-9
•
“Map to Different Value Types” on page 14-15
14 Map Containers
14-14
