TExcelTAD
Home › MATLAB / Octave › Key-Value Maps

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 dictionary type. Octave doesn't have it yet, so this course uses containers.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:

matlab · try it yourself
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:

matlab · try it yourself
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')
end
staples: 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:

matlab · try it yourself
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));
end
200 -> 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:

matlab · try it yourself
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}));
end
and   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:

matlab · try it yourself
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'?

  1. m.has('pear')
  2. isKey(m, 'pear')
  3. isfield(m, 'pear')
  4. exist(m('pear'))

In what order does keys(m) return text keys?

  1. Insertion order
  2. Random order
  3. Sorted alphabetically
  4. Reverse insertion order

After b = a; b('k') = 1; where a is a containers.Map, does a contain 'k'?

  1. Yes, because maps are handle objects
  2. No, b is a copy
  3. Only in Octave
  4. It is an error