How to access all the variables inside struct
28 ビュー (過去 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!