How can I iterate over the keys and elements in a containers.Map?
152 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
採用された回答
KSSV
2016 年 10 月 14 日
編集済み: KSSV
2016 年 10 月 14 日
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 件のコメント
Steven Lord
2016 年 10 月 14 日
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
その他の回答 (2 件)
Qixiang Zou
2017 年 8 月 11 日
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.
0 件のコメント
Clark Steen
2024 年 11 月 8 日 4:41
Alternatively, using strings:
D = containers.Map('air',1);
for k = string(D.keys)
D(k)
end
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で NaNs についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!