how to get all the fields names and values of a structure and save them in excel?

Hello,
I need to account for all the structures and values of a Matlab code.
I would like to export the full list to an excel file.
Is this possible?
Thank you

3 Comments

"how to get all the fields names and values of a structure and save them in excel?"
"I need to account for all the structures and values of a Matlab code."
Those are two very different tasks. Which is the correct task?
say I have a structure name "data".
"data" has a number of children which have their on children etc.
I need the names and the values of all the members of the structure and export this to excel
thank you
Show us what the struct actually is...from your descrption it could be messy. Just how much so will depend on just how convoluted you've made it.

Sign in to comment.

 Accepted Answer

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.

More Answers (0)

Products

Release

R2024b

Asked:

on 27 Feb 2025

Commented:

on 2 Mar 2025

Community Treasure Hunt

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

Start Hunting!