MATLAB: How to access a field in a structure array using a cell array containing strings corresponding to these fields using a for cycle

cell arraysfor loopstructures

I would like to access different fields of a structure array using a for cycle, so I created a cell array containing the same strings used to indexing the structure array but I am returned errors because the format to access a structure array needs a string after the point. As an example, if I have a structure array named A, and the cell array indicating the fields of the structure array is B, I would like to do the subsequent thing:
B={'first','second','third','fourth','fifth'};
for i=1:length(b)
A.B(i)=A.B(i)+1
end
to avoid doing the following thing manually:
A.first=A.first+1;
A.second=A.second+1;
A.third=A.third+1;
A.fourth=A.fourth+1;
A.fifth=A.fifth+1;
but in the for cycle Matlab is searching for the string B, that obviously doesn't exist. I would use such a for cycle to avoid to manually enter every single string. Does anybody know how to do that? Thanks for helping.

Best Answer

You almost had the syntax correct. Use "dynamic field names" by enclosing the field name variable (in this case B{i}) inside parentheses:
B={'first','second','third','fourth','fifth'};
for i=1:length(B)
A.(B{i}) = A.(B{i})+1;
end