Add 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;
Start with the Map ticketMap :
ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});
Add two more entries to the ticketMap Map. Verify that ticketMap now has six key/value pairs:
ticketMap('947F4') = 'Susan Spera';
ticketMap('417R93') = 'Patricia Hughes';
ticketMap.Count
ans =
6
List all of the keys and values in ticketMap:
keys(ticketMap), values(ticketMap)
ans =
'2R175'
'417R93'
'947F4'
'A479GY'
'B7398'
'NZ1452'
ans =
'James Enright'
'Patricia Hughes'
'Susan Spera'
'Sarah Latham'
'Carl Haynes'
'Bradley Reid'
Build 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 Map objects, 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:
• Only vertical vectors of Map objects are allowed. You cannot create an m-by-n array or a
horizontal vector of Map objects. For this reason, vertcat is supported for Map objects, but not
horzcat.
• All keys in each Map being concatenated must be of the same class.
• You can combine Maps with different numbers of key/value pairs. The result is a single Map object
containing key/value pairs from each of the contributing Map objects:
tMap1 = containers.Map({'2R175', 'B7398', 'A479GY'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham'});
14 Map Containers
14-10
Précédent

- 578/1450

Suivant