How can I iterate over the keys and elements in a containers.Map?
149 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Diego Mancevo
el 14 de Oct. de 2016
Respondida: Clark Steen
el 8 de Nov. de 2024 a las 4:41
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 comentarios
Respuesta aceptada
KSSV
el 14 de Oct. de 2016
Editada: KSSV
el 14 de Oct. de 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 comentarios
Steven Lord
el 14 de Oct. de 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
Más respuestas (2)
Qixiang Zou
el 11 de Ag. de 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.
0 comentarios
Clark Steen
el 8 de Nov. de 2024 a las 4:41
Alternatively, using strings:
D = containers.Map('air',1);
for k = string(D.keys)
D(k)
end
0 comentarios
Ver también
Categorías
Más información sobre NaNs en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!