How to access all the variables inside struct

13 views (last 30 days)
I have a cell. inside the cell there is a struct. again inside struct there is a cell. Again inside the cell there are 20 structs. Each struct now has 5 field values. I want to save all the field variable values individually in .mat format. How to access those field values and save it ?
  1 Comment
Stephen23
Stephen23 on 6 Sep 2024
"How to access those field values and save it ?"
The easiest way depends on the sizes of all of those cell arrays and structure arrays, which you did not tell us. Are they scalar or non-scalar? Nor did you tell us the names of the structure fields:
I have a cell. inside the cell there is a struct. again inside struct there is a cell. Again inside the cell there are 20 structs. Each struct now has 5 field values.
% ^^^^^^ what size?
% ^^^^^^^^ what size?
% ^^^^^^^^ what fieldnames?
% ^^^^^^ what size?
% ^^^^^^^^^^ 20 scalar structs or 1 non-scalar struct?
The easiest way for you to get help with this is to upload the data in a MAT file by clicking the paperclip button.

Sign in to comment.

Accepted Answer

Piyush Kumar
Piyush Kumar on 6 Sep 2024
Check this example -
% Sample data structure
mainCell = {struct('innerCell', {{struct('field1', 1, 'field2', 2, 'field3', 3, 'field4', 4, 'field5', 5), ...
struct('field1', 6, 'field2', 7, 'field3', 8, 'field4', 9, 'field5', 10)}})};
% Loop through the main cell
for i = 1:length(mainCell)
nestedStruct = mainCell{i}; % Access the struct inside the cell
% Loop through the inner cell
for j = 1:length(nestedStruct.innerCell)
innerStruct = nestedStruct.innerCell{j}; % Access the struct inside the inner cell
fields = fieldnames(innerStruct); % Get all field names
% Loop through each field
for k = 1:length(fields)
fieldValue = innerStruct.(fields{k}); % Access each field value
disp(fieldValue)
% Save each field value to a .mat file
save(['field_' num2str(i) '_' num2str(j) '_' fields{k} '.mat'], 'fieldValue');
end
end
end
1 2 3 4 5 6 7 8 9 10
I have created an example as per your description of the data structure. Let me know if it helps!

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!