Exporting a cell structure from Matlab to Excel

1.1k Views Asked by At

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 ?

1

There are 1 best solutions below

0
On

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);