How can I iterate over the keys and elements in a containers.Map?

149 views (last 30 days)
D = containers.Map('air',1)
for k = keys(D)
D(k)
end
Error using containers.Map/subsref
Specified key type does not match the type expected for this container.
Why does the above cause an error?

Accepted Answer

KSSV
KSSV on 14 Oct 2016
Edited: KSSV on 14 Oct 2016
D = containers.Map({'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});
k = keys(D) ;
val = values(D) ;
for i = 1:length(D)
[k{i} val{i}]
end
  2 Comments
Steven Lord
Steven Lord on 14 Oct 2016
The code in the original question was very close. The reason it didn't work is because the keys in D are char vectors
>> D = containers.Map({'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'})
D =
Map with properties:
Count: 4
KeyType: char
ValueType: char
The keys method returns a cell array, each cell of which contains one of the char vectors, not a char array itself. This allows containers.Map to return a set of char vector keys that are not the same length without needing to pad the shorter ones to the same length as the longest. To index into D, extract the char vectors from the cell array and use those char vectors as the index.
for k = keys(D)
thekey = k{1}; % The curly braces are the key, so to speak
fprintf('The value associated with key %s is %s.\n', ...
thekey, D(thekey));
end

Sign in to comment.

More Answers (2)

Qixiang Zou
Qixiang Zou on 11 Aug 2017
D = containers.Map('air',1)
for k = keys(D)
D(k{1}})
end
This should work. Iterator of cell returns element wrapped in a cell. So, add a stupid {1} can save your code.

Clark Steen
Clark Steen on 8 Nov 2024 at 4:41
Alternatively, using strings:
D = containers.Map('air',1);
for k = string(D.keys)
D(k)
end
ans = 1

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!