Unrecoginized Fieldname although it should be correctly defined

46 views (last 30 days)
Sven on 14 Aug 2023
Answered: Steven Lord on 14 Aug 2023
Hi,
Im trying to create a for loop to shorten my code, but i am running into some issues. My code is as followed:
% Define the joint names
jointNames = {'Knee', 'Ankle', 'Hip', 'Shoulder', 'Elbow'};
% Define the movement directions
directions = {'maxX', 'minX', 'maxY', 'minY', 'maxZ', 'minZ'};
% Initialize a structure to hold the mean angles
meanAngles = struct();
% Loop through each joint and direction
for j = 1:length(jointNames)
jointName = jointNames{j};
for d = 1:length(directions)
direction = directions{d};
% Construct the field name for the data
fieldName = ['RangeAnglesLeft.' direction '.' jointName];
% Calculate the mean angle for each condition (Nwalk and Wwalk)
meanAngleN = mean(cell2mat(Nwalk.(fieldName)));
meanAngleW = mean(cell2mat(Wwalk.(fieldName)));
% Store the mean angles in the structure
fieldMaxName = ['Max' jointName(1:end-1) direction];
fieldMinName = ['Min' jointName(1:end-1) direction];
meanAngles.(fieldMaxName).(['N' fieldMinName]) = meanAngleN;
meanAngles.(fieldMinName).(['W' fieldMaxName]) = meanAngleW;
end
end
Somehow there is an error with the fieldname. The error states: Unrecognized field name "RangeAnglesLeft.maxX.Knee".
Nwalk and Wwalk are a large dataset containing RangeAnglesLeft. This variable is a struct which can retrieve data by being called out as followed: Nwalk.RangeAnglesLeft.maxX.Knee. Somehow in the code above, it tells me that RangeAnglesLeft.maxX.Knee is not recognized. Can anyone help me with this problem?
Stephen23 on 14 Aug 2023
"This variable is a struct which can retrieve data by being called out as followed: Nwalk.RangeAnglesLeft.maxX.Knee"
No, that is exactly the problem: what you have are nested structures, not a structure. Any structure that happens to be stored inside another structure is still its own structure, which requires its own field references.
Once you understand that, then this mistake is easy to avoid.

Florian Bidaud on 14 Aug 2023
Edited: Florian Bidaud on 14 Aug 2023
You can't use dots in your fieldname. The dot creates a new field in the structure, but it can't be done directly in the name of the field with a char array or a string.
fieldName = ['RangeAnglesLeft.' direction '.' jointName];
% Calculate the mean angle for each condition (Nwalk and Wwalk)
meanAngleN = mean(cell2mat(Nwalk.(fieldName)));
You should do something like:
meanAngleN = mean((Nwalk.RangeAnglesLeft.(direction).(jointName));

Steven Lord on 14 Aug 2023
As others have said, you cannot index into a multi-level struct array using the .() notation like that. For this you'd probably want to use getfield.
A = struct('x', struct('b', 2, 'c', 3), 'y', 42)
A = struct with fields:
x: [1×1 struct] y: 42
fieldsToRetrieve = {'x', 'c'};
three = getfield(A, fieldsToRetrieve{:}) % Equivalent of A.x.c
three = 3
check = A.x.c
check = 3