Ask Your Question
1

How can I iterate through various fields of a struct in Matlab that have the same struct type?

asked 2022-09-20 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-03-10 00:00:00 +0000

pufferfish gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-20 11:00:00 +0000

Seen: 11 times

Last updated: Mar 10 '22