How to access all the variables inside struct

조회 수: 15 (최근 30일)
ANUSAYA SWAIN
ANUSAYA SWAIN 2024년 9월 6일
답변: Piyush Kumar 2024년 9월 6일
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
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
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
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!

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by