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

9 次查看(过去 30 天)
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 个评论
Pierre
Pierre 2025-2-27
编辑:Pierre 2025-2-27
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 2025-2-27
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.

请先登录,再进行评论。

采纳的回答

Umar
Umar 2025-2-27

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 个)

产品


版本

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by