【问题标题】:Matlab function to convert a struct to a struct arrayMatlab函数将结构转换为结构数组
【发布时间】:2023-04-08 21:43:01
【问题描述】:

我有一个格式为:

my_struct
   |
   + element_1
   |     |
   |     + value_1: "some string"
   |     + value_2: 25
   |
   + element_2
   |     |
   |     + value_1: "some other string"
   |     + value_2: 11
   ...

并且找不到一种简单的方法来创建一个结构数组,例如my_struct(1).value_1 == "some string"。同样,my_struct(2).value_2 == 11。字段名称“element_1”和“element_2”是不必要的。

【问题讨论】:

  • 您尝试过简单的循环吗? out(ii)=my_struct.(['element_',num2str(ii)]);

标签: arrays matlab struct


【解决方案1】:

这是一种方法(见struct2cellcell2mat):

result = cell2mat(struct2cell(my_struct).');

示例

my_struct.element_1.value1 = "some string"; 
my_struct.element_1.value2 = 25;
my_struct.element_2.value1 = "some other string"; 
my_struct.element_2.value2 = 11;
result = cell2mat(struct2cell(my_struct).');

给予

>> result
result = 
  1×2 struct array with fields:
    value1
    value2
>> result(1)
ans = 
  struct with fields:

    value1: "some string"
    value2: 25
>> result(2)
ans = 
  struct with fields:

    value1: "some other string"
    value2: 11

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 2014-11-13
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多