Key-Value Maps
Sometimes you want to look values up by a key that isn't a valid field name, or that is a number: a word count per word, a price per product code, a city per postcode. MATLAB's containers.Map is a dictionary (hash map) for exactly that. It works in MATLAB and in Octave.
Note: MATLAB R2022b added a newer
dictionarytype. Octave doesn't have it yet, so this course usescontainers.Map, which both programs support.
Creating a map
Create a map from a cell array of keys and a cell array of values, or start empty and add entries:
prices = containers.Map({'apple', 'bread', 'milk'}, {0.45, 2.10, 1.15});
fprintf('Bread costs %.2f\n', prices('bread'));
prices('cheese') = 4.80; % add a new key
prices('milk') = 1.25; % update an existing key
fprintf('%d items\n', prices.Count);
disp(keys(prices))
disp(cell2mat(values(prices)))Bread costs 2.10
4 items
{
[1,1] = apple
[1,2] = bread
[1,3] = cheese
[1,4] = milk
}
0.4500 2.1000 4.8000 1.2500
Keys come back sorted (alphabetically for text), and values(m) returns the values in the same order as keys(m).
Checking and removing keys
Reading a key that doesn't exist is an error, so check with isKey first. remove deletes an entry:
stock = containers.Map({'pens', 'paper'}, {120, 15});
item = 'staples';
if isKey(stock, item)
fprintf('%s: %d\n', item, stock(item));
else
fprintf('%s: not stocked\n', item);
end
disp(isKey(stock, {'pens', 'ink'}))
remove(stock, 'paper');
disp(keys(stock))
try
n = stock('paper');
catch err
disp('Reading a removed key raised an error')
endstaples: not stocked
1 0
{
[1,1] = pens
}
Reading a removed key raised an error
Numeric keys
By default keys are text ('KeyType' is 'char'). For numeric keys, specify the key and value types when creating an empty map:
codes = containers.Map('KeyType', 'double', 'ValueType', 'any');
codes(404) = 'Not Found';
codes(200) = 'OK';
codes(500) = 'Server Error';
k = cell2mat(keys(codes));
for n = k
fprintf('%d -> %s\n', n, codes(n));
end200 -> OK
404 -> Not Found
500 -> Server Error
'ValueType', 'any' allows any value; you can also restrict values to 'double', 'char' and other types.
Counting words
A map makes frequency counting easy:
sentence = 'the quick fox and the lazy dog and the cat';
words = strsplit(sentence, ' ');
counts = containers.Map();
for k = 1:numel(words)
w = words{k};
if isKey(counts, w)
counts(w) = counts(w) + 1;
else
counts(w) = 1;
end
end
allWords = keys(counts);
for k = 1:numel(allWords)
fprintf('%-5s %d\n', allWords{k}, counts(allWords{k}));
endand 2
cat 1
dog 1
fox 1
lazy 1
quick 1
the 3
Maps are handles
A containers.Map is a handle object: assigning it to another variable does not copy it. Both names refer to the same map, so a change through one is visible through the other. This differs from arrays, cells and structs, which are always copied:
a = containers.Map({'x'}, {1});
b = a; % same map, not a copy
b('y') = 2;
fprintf('a has %d keys\n', a.Count);
s1.x = 1;
s2 = s1; % structs are copied
s2.y = 2;
fprintf('s1 has %d fields\n', numel(fieldnames(s1)));a has 2 keys
s1 has 1 fields
Map, struct or arrays?
| Need | Use |
|---|---|
| Fixed, known names | struct |
| Keys from data (any text, numbers) | containers.Map |
| Keys are small consecutive integers | A plain array indexed by the key |
Two parallel lists you search with strcmp/ismember |
Fine for small data |
Test yourself
How do you test whether the map m has the key 'pear'?
m.has('pear')isKey(m, 'pear')isfield(m, 'pear')exist(m('pear'))
In what order does keys(m) return text keys?
- Insertion order
- Random order
- Sorted alphabetically
- Reverse insertion order
After b = a; b('k') = 1; where a is a containers.Map, does a contain 'k'?
- Yes, because maps are handle objects
- No,
bis a copy - Only in Octave
- It is an error