Suppose I have a struct:
假设我有一个结构体:
myStruct = struct()
myStruct.a = 1;
myStruct.b = 20;
myStruct.c = 4;
Is it possible to convert it to map where the keys are the struct fields? For example, myMap('a')
should return 1
.
是否有可能将它转换为映射键在struct字段中的位置?例如,myMap('a')应该返回1。
1 个解决方案
#1
5
It can be done as follows:
可以这样做:
myMap = containers.Map(fieldnames(myStruct), struct2cell(myStruct));
This uses the syntax myMap = containers.Map(keys, values)
, where
这使用语法myMap =容器。地图(键值),
-
keys
is a cell array of the field names ofmyStruct
, generated by the functionfieldnames
; - 键是由函数fieldnames生成的myStruct字段名的单元数组;
-
values
is a cell array of the values ofmystruct
, obtained withstruct2cell
. - 用struct2cell获得的mystruct值的单元格数组。
#1
5
It can be done as follows:
可以这样做:
myMap = containers.Map(fieldnames(myStruct), struct2cell(myStruct));
This uses the syntax myMap = containers.Map(keys, values)
, where
这使用语法myMap =容器。地图(键值),
-
keys
is a cell array of the field names ofmyStruct
, generated by the functionfieldnames
; - 键是由函数fieldnames生成的myStruct字段名的单元数组;
-
values
is a cell array of the values ofmystruct
, obtained withstruct2cell
. - 用struct2cell获得的mystruct值的单元格数组。