【问题标题】:MATLAB: How to tabulate structs with same fieldsMATLAB:如何将具有相同字段的结构制成表格
【发布时间】:2017-07-17 10:11:39
【问题描述】:

我使用了一个名为 data 的 428×1 元胞数组

data = {[1×1 struct]
        [1×1 struct]
        ....
        [1x1 struct]}

这些结构都具有相同的结构

data {2,1}

>>struct with fields

         additional_model_information: 'H Series,S3150-S0-AW-04-02-C-F421,'
 ceiling_fan_size_diameters_in_inches: '60'
      airflow_efficiency_cfm_watt_low: '727'
     airflow_efficiency_cfm_watt_high: '392'

所有 428 个单元的结构字段都相同,并且每个结构中的字段值都不同。

如何创建一个将所有结构放在一起的表,以便显示每个字段的所有字段值?也许使用嵌套的 for 循环?

我最终想将此数据导出到 excel。

【问题讨论】:

  • 您使用的是什么版本的 Matlab?您是否真的希望 table 中的这些数据,或者只要您可以导出到 Excel,cell array 就可以工作?
  • MATLAB R2017a。只要我可以导出到 Excel @Wolfie

标签: arrays excel matlab


【解决方案1】:

假设你有你的 nx1 结构单元数组,data。此方法不假设您的数据中有 4 个字段,也不知道它们的名称。如果您包含一些 try/catch 逻辑,您甚至可以将它与具有不同字段名的结构一起使用。


您可以使用fieldnames获取代表结构的字段名称

fnames = fieldnames(data{1});

然后设置一些正确大小的输出元胞数组out

out = cell(numel(fnames), numel(data));

然后使用嵌套循环1.遍历data中的项目和2.遍历字段名称。

for n = 1:numel(data)
    for field = 1:numel(fnames)
        temp = data{n};
        out{field, n} = temp.(fnames{field});
    end
end

最后,追加字段名作为第一列

out = [fnames, out];

并将元胞数组写入您的 Excel 文件

%        File location,      cell array,  sheet,  cell
xlswrite('C:\...\test.xlsx', out,         1,      'A1');

【讨论】:

  • 谢谢。我得到了这个回应:引用不存在的字段“additional_model_information”。无标题(第 8 行)错误 out{field, n} = temp.(fnames{field});
  • 这意味着data{n} 中的结构不包含additional_model_information 字段...尝试在try; out{field, n} = temp.(fnames{field}); ; catch; end; 中包围out{field, n} 行。你最终会得到一个空单元格元素,你期望该字段,但它会跳过错误。
  • 非常感谢。它工作得很好。我刚刚发现数据 {n} 中的结构包含数字、文本和 floating_timestamp
  • 啊,很高兴我能帮上忙……如果它解决了您的问题,请考虑将此答案标记为已接受 :)
  • 我会的。谢谢
【解决方案2】:

怎么样

T = cell(length(data) , 4);
for k = 1 : length(data)
   T(k , :) = {data{k}.additional_model_information , ...
               data{k}.ceiling_fan_size_diameters_in_inches, ...
               data{k}.airflow_efficiency_cfm_watt_low, ...
               data{k}.airflow_efficiency_cfm_watt_high};
end

然后就可以使用xlswrite导出到excel了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    相关资源
    最近更新 更多