迭代MATLAB中的struct fieldnames

noi*_*oio 69 matlab matlab-struct

我的问题很容易归纳为:"为什么以下不起作用?"

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

fields = fieldnames(teststruct)

for i=1:numel(fields)
  fields(i)
  teststruct.(fields(i))
end
Run Code Online (Sandbox Code Playgroud)

输出:

ans = 'a'

??? Argument to dynamic structure reference must evaluate to a valid field name.
Run Code Online (Sandbox Code Playgroud)

特别是因为teststruct.('a') 确实有效.并fields(i)打印出来ans = 'a'.

我无法理解它.

gno*_*ice 91

您必须使用花括号({})来访问fields,因为该fieldnames函数返回字符串的单元格数组:

for i = 1:numel(fields)
  teststruct.(fields{i})
end
Run Code Online (Sandbox Code Playgroud)

使用括号访问单元格数组中的数据将只返回另一个单元格数组,该数组与字符数组的显示方式不同:

>> 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
Run Code Online (Sandbox Code Playgroud)

  • 你的回答非常有用,并且已经清除了一些多年来一直困扰我的事情. (2认同)

Jon*_*nas 15

由于fields或是fns单元格数组,您必须使用大括号进行索引{}才能访问单元格的内容,即字符串.

请注意,您可以fields直接循环,而不是循环遍历数字,利用一个简洁的Matlab功能,可以让您遍历任何数组.迭代变量采用数组的每列的值.

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

fields = fieldnames(teststruct)

for fn=fields'
  fn
  %# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
  teststruct.(fn{1})
end
Run Code Online (Sandbox Code Playgroud)


And*_*nke 5

你的fns是一个celltr数组.您需要使用{}而不是()来索引它,以将单个字符串作为char输出.

fns{i}
teststruct.(fns{i})
Run Code Online (Sandbox Code Playgroud)

使用()索引到它将返回一个1长的cellstr数组,该数组与".(name)"动态字段引用所需的char数组的格式不同.格式化,特别是在显示输出中,可能会造成混淆.要看到差异,试试这个.

name_as_char = 'a'
name_as_cellstr = {'a'}
Run Code Online (Sandbox Code Playgroud)