74

我的问题很容易概括为:“为什么以下不起作用?”

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

fields = fieldnames(teststruct)

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

输出:

ans = 'a'

??? Argument to dynamic structure reference must evaluate to a valid field name.

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

我无法理解它。

4

4 回答 4

95

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

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

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

>> 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
于 2010-05-10T15:41:25.967 回答
15

由于fieldsorfns是元胞数组,您必须使用大括号进行索引{}才能访问元胞的内容,即字符串。

请注意,除了循环一个数字之外,您还可以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
于 2010-05-10T15:47:49.600 回答
5

你的 fns 是一个 cellstr 数组。您需要使用 {} 而不是 () 对其进行索引,以将单个字符串作为 char 输出。

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

使用 () 对其进行索引会返回一个 1 长的 cellstr 数组,该数组与“.(name)”动态字段引用所需的 char 数组的格式不同。格式,尤其是在显示输出中,可能会令人困惑。要查看差异,请尝试此操作。

name_as_char = 'a'
name_as_cellstr = {'a'}
于 2010-05-10T15:41:51.407 回答
1

您可以使用http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each中的 for each 工具箱。

>> signal
signal = 
sin: {{1x1x25 cell}  {1x1x25 cell}}
cos: {{1x1x25 cell}  {1x1x25 cell}}

>> each(fieldnames(signal))
ans = 
CellIterator with properties:

NumberOfIterations: 2.0000e+000

用法:

for bridge = each(fieldnames(signal))
   signal.(bridge) = rand(10);
end

我非常喜欢它。当然,这要归功于开发工具箱的 Jeremy Hughes。

于 2016-02-29T13:36:21.743 回答