One possible solution is to use a for loop to iteratively access each field of the struct that has the same struct type. Here's an example code:
% Define the struct with fields of the same type
myStruct.fieldA = struct('subFieldA', [], 'subFieldB', []);
myStruct.fieldB = struct('subFieldA', [], 'subFieldB', []);
% Iterate through the fields of the struct
fieldNames = fieldnames(myStruct);
for i = 1:numel(fieldNames)
% Get the current field name and value
fieldName = fieldNames{i};
fieldValue = myStruct.(fieldName);
% Check if the field value is a struct
if isstruct(fieldValue)
% Iterate through the subfields of the struct
subFieldNames = fieldnames(fieldValue);
for j = 1:numel(subFieldNames)
% Get the current subfield name and value
subFieldName = subFieldNames{j};
subFieldValue = fieldValue.(subFieldName);
% Do something with the subfield value
fprintf('Field %s.%s = %s\n', fieldName, subFieldName, num2str(subFieldValue));
end
else
% Do something with the non-struct field value
fprintf('Field %s = %s\n', fieldName, num2str(fieldValue));
end
end
This code defines a struct myStruct
with two fields (fieldA
and fieldB
) that have the same struct type. A for loop iterates through the fields of the struct, checks if the field value is a struct, and if so, iterates through the subfields of the struct. The subfield values are printed out using fprintf
, but you can replace this with any operation that you want to perform on the subfield values.
Asked: 2022-09-20 11:00:00 +0000
Seen: 11 times
Last updated: Mar 10 '22