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

8 visualizaciones (últimos 30 días)
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 comentarios
Pierre
Pierre el 27 de Feb. de 2025
Editada: Pierre el 27 de Feb. de 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 el 27 de Feb. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Umar
Umar el 27 de Feb. de 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.

Más respuestas (0)

Productos


Versión

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by