containers.Map — Create key-value dictionary objects in MATLAB and RunMat.
containers.Map creates dictionary objects that associate unique keys with values. Supported key kinds include character vectors, string scalars, and numeric/logical scalars; values default to 'any' storage semantics, with method behavior aligned to MATLAB and RunMat.
Syntax
M = containers.Map()
M = containers.Map(keys, values)
M = containers.Map(keys, values, Name, Value, ...)
M = containers.Map(Name, Value, ...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
keys | Any | Yes | — | Key container (cell, string/char, or numeric vector). |
values | Any | Yes | — | Value container aligned with keys. |
options | Any | Variadic | — | Name/value options (KeyType, ValueType, UniformValues, ComparisonMethod). |
Returns
| Name | Type | Description |
|---|---|---|
M | Any | containers.Map handle object. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:containers.Map:InvalidArgument | Map constructor/method inputs, option grammar, or key/value payloads are invalid. | containers.Map: invalid argument |
RunMat:containers.Map:MissingKey | Lookup/removal targets a key that is not present in the map. | containers.Map: The specified key is not present in this container. |
RunMat:containers.Map:Internal | Map registry/storage operations fail unexpectedly. | containers.Map: internal operation failed |
How containers.Map works
- Keys must be unique. Constructing a map or assigning a key that already exists overwrites the stored value (matching MATLAB's behaviour).
- The
KeyType,ValueType, andCountproperties are readable with dot-indexing. map(key)returns the associated value; requesting a missing key raises the MATLAB-compatible error *"The specified key is not present in this container."*- Assignments of the form
map(key) = valueupdate or insert entries. - Methods
keys(map),values(map),isKey(map, keySpec), andremove(map, keySpec)are fully compatible. WhenkeySpecis a cell or string array, the result matches MATLAB's shape. - GPU tensors presented as values are gathered to host memory before insertion. When values or keys arrive on the GPU and need to be expanded element-wise (for example, vector-valued constructor arguments), RunMat downloads them to materialise individual scalars.
- The
'UniformValues'flag is accepted; whentrue, RunMat validates that every inserted value has the same MATLAB class. Retrieval still returns a cell array, matching MATLAB behaviour when the value type is'any'.
Does RunMat run containers.Map on the GPU?
The data structure itself resides on the CPU. When you construct a map with GPU arrays, RunMat first downloads the inputs so it can perform MATLAB-compatible validation and coercion. Maps never retain device buffers internally, so the GPU provider does not need to implement special hooks for this builtin.
Examples
Create an empty map with default types
m = containers.Map();
m.KeyType
m.ValueType
m.CountExpected output:
ans =
'char'
ans =
'any'
ans =
0Build a map from paired cell arrays
keys = {'apple', 'pear', 'banana'};
vals = {42, [1 2 3], true};
fruit = containers.Map(keys, vals);
energy = fruit('apple')Expected output:
energy =
42Update an existing key and add a new one
fruit('apple') = 99;
fruit('peach') = struct('ripe', true)Expected output:
fruit('apple')
ans =
99Query keys, values, and membership
allKeys = keys(fruit);
allVals = values(fruit);
mask = isKey(fruit, {'apple', 'durian'})Expected output:
allKeys =
1×4 cell array
{'apple'} {'pear'} {'banana'} {'peach'}
allVals =
1×4 cell array
{[99]} {[1 2 3]} {[1]} {1×1 struct}
mask =
1×2 logical array
1 0Remove keys and inspect the map length
remove(fruit, {'pear', 'banana'});
n = length(fruit);
remaining = keys(fruit)Expected output:
n =
2
remaining =
1×2 cell array
{'apple'} {'peach'}Using containers.Map with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how containers.Map changes the result.
Run a small containers.Map example, explain the result, then change one input and compare the output.
FAQ
Which key types are supported?⌄
containers.Map accepts 'char', 'string', 'double', 'single', 'int32', 'uint32', 'int64', 'uint64', and 'logical'. Keys supplied during construction or assignment are coerced to the declared type and must be scalar.
What happens when I provide duplicate keys at construction time?⌄
Duplicate keys raise the same error as MATLAB: *"Duplicate key name was provided."* During assignment, duplicate keys overwrite the existing value.
Does RunMat honour 'UniformValues', true?⌄
Yes. When this option is set, RunMat enforces that each inserted value matches the MATLAB class of the first value. Retrieval still uses cell arrays, mirroring MATLAB when 'ValueType' is 'any'.
Can I store GPU arrays as map values?⌄
Yes. RunMat automatically gathers GPU tensors to host memory before inserting them so it can apply the same validation and coercion rules as MATLAB. This ensures constructors that rely on vector expansion continue to produce predictable host-side values.
How does length(map) behave?⌄
length(map) returns the number of stored keys (identical to the Count property). size(map) remains [1 1], matching MATLAB's handle semantics.
What error is raised when a key is missing?⌄
Indexing a missing key produces the MATLAB-compatible error message *"The specified key is not present in this container."*
Does the map preserve insertion order?⌄
Yes. keys(map) and values(map) return entries in the order they were first inserted, matching the behaviour of MATLAB's containers.Map.
Is the implementation thread-safe?⌄
Yes. A global read/write lock guards the backing storage so concurrent reads are allowed while write operations remain exclusive.
How do I remove every entry?⌄
Call remove(map, keys(map)) or reassign a new empty map. RunMat currently keeps the internal storage until the handle is cleared, matching MATLAB's lifetime semantics.
What happens if I pass a non-scalar key?⌄
Keys must be scalar. Passing vectors, matrices, or nested cell arrays of keys raises a descriptive error pointing to the offending argument.
How do I create an empty containers.Map?⌄
— Call the constructor with no arguments: m = containers.Map(). This yields an empty map with the default 'char' KeyType and 'any' ValueType. To pin the types up front (so the first insertion can't change them), supply them explicitly: m = containers.Map('KeyType', 'char', 'ValueType', 'double'). Either form gives you a map you can populate via m(key) = value.
What is the default KeyType and ValueType?⌄
— The default KeyType is 'char' and the default ValueType is 'any'. That is why containers.Map() with no arguments accepts character-vector keys and arbitrary values. To use numeric keys (for example double or int32) or to restrict values to a specific class, set 'KeyType'/'ValueType' at construction time — they become read-only properties afterwards.
Can I use MATLAB string values as containers.Map keys?⌄
— MATLAB's containers.Map only accepts scalar character vectors (or scalar numerics / logicals) as keys, not string scalars. Convert first with char(str) when you use a 'char' KeyType, e.g. m(char("apple")) = 1. RunMat additionally accepts 'string' as a KeyType alias that stores keys as character vectors internally, so either m = containers.Map('KeyType','char','ValueType','any') followed by m(char(s)) = v or constructing from cell arrays of char vectors works reliably across both runtimes.
Is containers.Map a handle class?⌄
— Yes. containers.Map inherits from handle, so maps have reference semantics: if you assign m2 = m1, both variables point to the same underlying map and mutations through either handle are visible through the other. To get an independent copy, rebuild the map from keys(m1) and values(m1) (for example, m2 = containers.Map(keys(m1), values(m1))). MATLAB does not expose a public copy method on containers.Map.
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how containers.Map is executed, line by line, in Rust.
- View the source for containers.Map in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.