How to iterate and access over map key values

49 ビュー (過去 30 日間)
Tabassum
Tabassum 2023 年 7 月 11 日
回答済み: Diwakar Diwakar 2023 年 7 月 11 日
I have a map with some keys which has multiple number of values in it How can I access those values for each key.
these show the size of the array of the value but not the values itself.
for u = keys(mp)
mu = values(mp,u);
disp(mu)
for v = mu
disp(v);
end
disp('-----------ended------------------')
end

回答 (2 件)

Chunru
Chunru 2023 年 7 月 11 日
mp = dictionary(["a1", "a2", "a3"], {1, [2 3], "str"})
mp =
dictionary (stringcell) with 3 entries: "a1" ⟼ {[1]} "a2" ⟼ {[2 3]} "a3" ⟼ {["str"]}
k = keys(mp);
v = values(mp)
v = 3×1 cell array
{[ 1]} {[ 2 3]} {["str"]}
for i = 1:length(v)
disp(v(i));
end
{[1]} {[2 3]} {["str"]}

Diwakar Diwakar
Diwakar Diwakar 2023 年 7 月 11 日
Check the below code may be help you.
% Create and populate the map
mp = containers.Map;
mp('key1') = [1, 2, 3];
mp('key2') = {'value1', 'value2', 'value3'};
mp('key3') = [10, 20, 30, 40];
% Iterate over each key in the map
for u = keys(mp)
key = u{1}; % Extract the key from the cell array
% Access the values associated with the current key
valuesArray = mp(key);
% Iterate over each value in the values array
for i = 1:numel(valuesArray)
value = valuesArray(i);
disp(value);
end
disp('-----------ended------------------')
end
1 2 3
-----------ended------------------
{'value1'} {'value2'} {'value3'}
-----------ended------------------
10 20 30 40
-----------ended------------------

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by