Export Data to excel spreadsheet from Structure Array Dynamically (Without Knowing the field Names)

3 views (last 30 days)
Hello, I am able to read data from xml file to a matlab structure array. I need to export data from structure array to excel in a table like structure.
the data i need from structure is like :
'code structure:
s = parseChildNodes(xDoc); % getting all data in a structure s
'data needed and field name s.catalog.book{1,1}.author
Given I don't know any field names or structures like catalog,book,author
Thanks for your help.

Accepted Answer

James Kristoff
James Kristoff on 27 May 2014
Edited: James Kristoff on 27 May 2014
There are many useful functions to know when working with structures in MATLAB. First is the function fieldnames which will return a cell array of all the names of all the fields in the structure e.g.
given a structure:
foo.bar_1 = 6;
foo.bar_2 = 'hello';
foo.bar_3 = [1,2,3];
the command:
names = fieldnames(foo);
will make the variable names =
{'bar_1'; 'bar_2'; 'bar_3'}
Once you have the field names in a cell array you can access the data in the structure in a loop e.g.
for( i = 1:length(names) )
% get the data
tempData = foo.(names{i});
% do something with the data
end
this uses the fact that you can access the fields of a structure using a string, or a variable containing a string, if you wrap it in parenthesis.
Actually sending this data to an excel sheet will depend greatly on the format of your data and how you want to store it in the spreadsheet. To do this you should use the function xlswrite.
  2 Comments
Varun Kumar
Varun Kumar on 28 May 2014
Thanks A lot James Kristoff.but suppose my data is at 's.catalog.book{1,1}.author'. Can we write a recursive function?
James Kristoff
James Kristoff on 28 May 2014
You can definitely write a recursive function. The syntax I mentioned that allows you to use a string or a variable to access a field of a structure can be used for multiple layers e.g.
% defines a structure that contains a structure
% and a structure that contains a cell array that contains a structure.
foo.bar_1 = 6;
foo.bar_2 = 'hello';
foo.bar_3.foobar_1 = [1,2,3];
foo.bar_4 = {struct('foobar_2', 'hello')};
% access the struc in a struct
foo.('bar_3').('foobar_1')
% access a struct in a cell array in a struct
foo.('bar_4'){1}.('foobar_2')
Some additional functions you might find helpful:
Test if a variable is a structure
Test if a field exists in a structure

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!