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 ExchangeStructures についてさらに検索

質問済み:

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