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

8 vues (au cours des 30 derniers jours)
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 commentaires
Pierre
Pierre le 27 Fév 2025
Modifié(e) : Pierre le 27 Fév 2025
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
dpb
dpb le 27 Fév 2025
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.

Connectez-vous pour commenter.

Réponse acceptée

Umar
Umar le 27 Fév 2025

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.

Plus de réponses (0)

Produits


Version

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by