How can I access a field in a structure array using a cell array containing strings corresponding to these fields using a for cycle?

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.

 채택된 답변

James Tursa
James Tursa 2016년 10월 14일
편집: James Tursa 2016년 10월 14일
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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

질문:

2016년 10월 14일

편집:

2016년 10월 14일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by