简体   繁体   中英

Exporting a cell structure from Matlab to Excel

I have a cell structure which has <1*40 struct> inside it. Every structure has the same field names (each having 12 field names and respective values). I want to Export this cell Array into an Excel file such that all the field names become the heading (12 consecutive columns), and below each field Name Comes its respective field values.

I have tried xlswrite by using cell2struct but it does not help.
If anyone could help me with this ?

If your input data looks something like this:

data = {struct('a', 1, 'b', 2), struct('a', 3, 'b', 4)};

You can process it using a combination of struct2cell and simple concatenation.

First convert from a cell array to an array of structs:

data = cat(2, data{:});

Then you can get the values using struct2cell

values = struct2cell(data(:));

Then the column names should simply be the fieldnames of your struct

headers = fieldnames(data);

Then you can concatenate the headers with the data to yield the input to xlswrite

xlsdata = cat(2, headers, values)'
xlswrite('filename.xlsx', xlsdata);

xlsdata =

    'a'    'b'
    [1]    [2]
    [3]    [4]

We can condense this a little bit:

xlsdata = cat(2, fieldnames(data{1}), struct2cell(cat(2, data{:})))';
xlswrite('filename.xlsx', xlsdata);

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