MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Read and Write Using 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.

NoteFor a large Map, the keys and value methods use a lot of memory as their outputs
are cell arrays.

Read From 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 vector, enclose it
in single quotation marks:

valueN = mapObj(keyN);

Start with the Map ticketMap :

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

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?

Read and Write Using Key Index
Free download pdf