在Matlab中是否可以将结构转换为映射?

时间:2021-09-22 20:48:24

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 of myStruct, generated by the function fieldnames;
  • 键是由函数fieldnames生成的myStruct字段名的单元数组;
  • valuesis a cell array of the values of mystruct, obtained with struct2cell.
  • 用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 of myStruct, generated by the function fieldnames;
  • 键是由函数fieldnames生成的myStruct字段名的单元数组;
  • valuesis a cell array of the values of mystruct, obtained with struct2cell.
  • 用struct2cell获得的mystruct值的单元格数组。