loop through the fields of a structure in matlab

One way to loop through the fields of a structure in Matlab is to use the fieldnames function to get a list of all the field names, and then loop through that list. Here's an example:

main.m
% Define a sample structure
myStruct.field1 = 'foo';
myStruct.field2 = 42;
myStruct.field3 = [1, 2, 3];

% Get a list of all field names
fieldList = fieldnames(myStruct);

% Loop through the field names and access each field
for iField = 1:length(fieldList)
    fieldName = fieldList{iField};
    fieldValue = myStruct.(fieldName);
    fprintf('Field name: %s, Field value: %s\n', fieldName, num2str(fieldValue));
end
418 chars
15 lines

In this example, we define a sample structure with three fields (field1, field2, and field3). We then use fieldnames to get a list of all the field names, and loop through that list using a for loop. Inside the loop, we access each field using dot notation (myStruct.(fieldName)) and print out its name and value using fprintf.

gistlibby LogSnag