Iterating through struct fieldnames in MATLAB

前端 未结 4 833
说谎
说谎 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条回答
  •  Happy的楠姐
    2020-11-30 21:16

    You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:

    for i = 1:numel(fields)
      teststruct.(fields{i})
    end
    

    Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:

    >> fields(1)  % Get the first cell of the cell array
    
    ans = 
    
        'a'       % This is how the 1-element cell array is displayed
    
    >> fields{1}  % Get the contents of the first cell of the cell array
    
    ans =
    
    a             % This is how the single character is displayed
    

提交回复
热议问题