Iterating through struct fieldnames in MATLAB

前端 未结 4 819
说谎
说谎 2020-11-30 20:24

My question is easily summarized as: \"Why does the following not work?\"

teststruct = struct(\'a\',3,\'b\',5,\'c\',9)

fields = fieldnames(teststru         


        
4条回答
  •  無奈伤痛
    2020-11-30 21:26

    Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.

    fns{i}
    teststruct.(fns{i})
    

    Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.

    name_as_char = 'a'
    name_as_cellstr = {'a'}
    

提交回复
热议问题