how to get all the fields names and values of a structure and save them in excel?
3 个评论
采纳的回答
Hi @Pierre,
To achieve this task in MATLAB, you can utilize a recursive function to traverse through the structure and collect the names and values of all its members. Once you have this information, you can use the writetable function to export the data to an Excel file. Below is an example code snippet that demonstrates this process:
function exportStructToExcel(data, filename) % Initialize cell arrays to hold names and values names = {}; values = {};
% Recursive function to traverse the structure function traverseStruct(s, parentName) fields = fieldnames(s); for i = 1:length(fields) fieldName = fields{i}; fullName = [parentName, '.', fieldName]; value = s.(fieldName); if isstruct(value) traverseStruct(value, fullName); % Recursive call for nested structures else names{end+1} = fullName; % Store the full name values{end+1} = value; % Store the value end end end
% Start traversing from the root structure traverseStruct(data, 'data');
% Create a table and write to Excel T = table(names', values', 'VariableNames', {'Name', 'Value'}); writetable(T, filename); end
% Example usage data.a = 1; data.b.child1.c = 2; data.b.child2.d = 3; exportStructToExcel(data, 'output.xlsx');
Please see attached.

In this example, the function exportStructToExcel takes the structure data and a filename as inputs. It recursively collects the names and values of all members and exports them to an Excel file named 'output.xlsx'. The final result will be a neatly organized Excel file containing the hierarchical names and their corresponding values.
更多回答(0 个)
另请参阅
类别
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!