MATLAB Answers

How to save struct data from struct to excel?

847 views (last 30 days)
Ann G
Ann G on 4 Dec 2015
Answered: Raj Sodhi on 29 Sep 2019
How can I save the output data of my matlab code in an excel file when the data are struct?

  0 Comments

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 4 Dec 2015
We could do with a lot more details about what you want to do. Do you want the field names to be saved? Is the structure scalar or an array? But at the simplest:
writetable(struct2table(yourstructure), 'someexcelfile.xlsx')
Note that Excel is a tabular format, whereas structures are not. The two are not really the same thing.

  11 Comments

Show 8 older comments
Guillaume
Guillaume on 8 Dec 2015
You're not causing trouble. I was trying to convey to you that giving more (and accurate) details of what you have and want would make it much easier to answer your question.
In this case, we needed to know that you had a scalar structure where all the fields contained row vectors of identical size.
The solution was therefore to concatenate the row vectors vertically into a matrix and pass that to excel.
Muhammad Amirul Hafiz Sahful Bahri
I have an error something like this,
Error using struct2table (line
26)
Input structure must be a
scalar structure, or a
structure array with one column
or one row.
Error in beginner (line 17)
writetable(struct2table(S{1,1}),'someexcelfile.xlsx');
How can i solve this problem?

Sign in to comment.

More Answers (1)

Raj Sodhi
Raj Sodhi on 29 Sep 2019
In some cases you have a struct as an element of a struct. So I found it necessary to find only those an output those to the Excel file.
txt = fieldnames(strct) ;
sel = ones(size(txt)) ;
for i = 1:length(txt)
sel(i) = isstruct(strct.(txt{i})) ;
end
i_not_struct = find(~sel) ;
i_struct = find(sel) ;
x = [fieldnames(strct) struct2cell(strct)] ;
xlswrite(xlsfile ,x(i_not_struct,:),1,'a1') ; % winopen(xlsfile)
Then I treat the struct elements separately, as shown in the attached file.
Yours,
Raj

  0 Comments

Sign in to comment.

Sign in to answer this question.