Export Data to excel spreadsheet from Structure Array Dynamically (Without Knowing the field Names)
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
James Kristoff
2014-5-27
编辑:James Kristoff
2014-5-27
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 个评论
James Kristoff
2014-5-28
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!