Using array or vector as a key in Map

8 ビュー (過去 30 日間)
keenu
keenu 2017 年 7 月 1 日
編集済み: Bradley Stiritz 2020 年 8 月 2 日
In C++ we can use arrays or vector as a key against to a int value like: map<vector<int> ,int > m; Can I do same in MATLAB by containers.Map(keySet,valueSet) or by other means?? If yes,please post code. Thanks...

回答 (2 件)

Walter Roberson
Walter Roberson 2017 年 7 月 1 日
Yes. The very first example at https://www.mathworks.com/help/matlab/ref/containers.map-class.html shows using a string as a key.
  2 件のコメント
keenu
keenu 2017 年 7 月 1 日
編集済み: Walter Roberson 2017 年 7 月 1 日
I think you don't understand my question. I want to use vector or array as the key against int value like:
[2,3,4]->1 [5,4]->2 [1,9,10,12]->3 [7]->4
and so on.....
Can now you help me????
Walter Roberson
Walter Roberson 2017 年 7 月 1 日
In that case, you can sprintf() the vector into a string and use the string as the index.
Alternately, you could use one of the Serialization routines in the File Exchange to construct a byte array representing the arbitrary object you wish to use to index, and then convert the byte array to a string. I do not know at the moment whether using char(0) in a key would be permitted, but certainly converting to hex would work.

サインインしてコメントする。


Bradley Stiritz
Bradley Stiritz 2020 年 8 月 2 日
編集済み: Bradley Stiritz 2020 年 8 月 2 日
@Walter-- I couldn't get your sprintf() suggestion to work, maybe I didn't understand you? I have included my own proposed solution below--
% Create simple Map object with keys and values
>> CMap_ = containers.Map(["1","2"],["A","B"])
CMap_ = Map with properties:
Count: 2
KeyType: char
ValueType: char
% Create a vector of keys, for which we want a corresponding output vector of values.
% Note column vector usage, important below.
>> key_vector = ["2";"1";]
key_vector = 2×1 string array
"2"
"1"
% For input key vector ["2"; "1";], we expect to get output values vector ["B"; "A";].
% However, this fails--
>> CMap_(key_vector)
Error using containers.Map/subsref
Specified key type does not match the type expected for this
container.
% Walter> "sprintf() the vector into a string and use the string as the index"
% We use strjoin() for simplicity here--
>> mashup_key = strjoin(key_vector,"")
mashup_key = "21"
% Concatenated key doesn't exist within the Map
>> CMap_(mashup_key)
Error using containers.Map/subsref
The specified key is not present in this container.
% My own proposed workaround solution--
>> string(arrayfun(@(x)CMap_(x),key_vector))
ans = 2×1 string array
"B"
"A"

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by