简体   繁体   中英

MATLAB: How to tabulate structs with same fields

I have use a 428×1 cell array called data

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

These struct all have the same structure

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'

The structure fields are the same for all 428 cells, and the fields values change in each struct.

How could i create a table that puts all of the structs together so that it shows all of the field values for each field? Pehaps using a nested for loop?

I eventually want to export this data to excel.

How about

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

Then you can use xlswrite to export to excel.

Let's say you've got your nx1 cell array of structs, data . This method doesn't assume you have 4 fields in your data or any knowledge of what they are called. You could even use it with structs with different fieldnames if you included some try / catch logic.


You can get the field names of a representative struct using fieldnames

fnames = fieldnames(data{1});

Then set up some output cell array out of the correct size

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

Then use nested loops to 1. loop through items in data and 2. loop through field names.

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

Finally, append the field names as the first column

out = [fnames, out];

And write the cell array to your Excel file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM