How to access all the variables inside struct
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
ANUSAYA SWAIN
el 6 de Sept. de 2024
Respondida: Piyush Kumar
el 6 de Sept. de 2024
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 comentario
Stephen23
el 6 de Sept. de 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.
Respuesta aceptada
Piyush Kumar
el 6 de Sept. de 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
I have created an example as per your description of the data structure. Let me know if it helps!
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!