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

조회 수: 61 (최근 30일)
Diego Mancevo
Diego Mancevo 2016년 10월 14일
답변: Clark Steen 2024년 11월 8일
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?

채택된 답변

KSSV
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
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
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.

Clark Steen
Clark Steen 2024년 11월 8일
Alternatively, using strings:
D = containers.Map('air',1);
for k = string(D.keys)
D(k)
end
ans = 1

카테고리

Help CenterFile Exchange에서 Polynomials에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by