How to access all the variables inside struct
14 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2024-9-6
"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.
采纳的回答
Piyush Kumar
2024-9-6
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
I have created an example as per your description of the data structure. Let me know if it helps!
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!