我的问题很容易概括为:“为什么下面的问题不起作用?”
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'
。
我就是想不通。
发布于 2010-05-10 23:41:26
您必须使用大括号({}
)来访问fields
,因为fieldnames
函数返回字符串的cell array:
for i = 1:numel(fields)
teststruct.(fields{i})
end
对access data in your cell 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
发布于 2010-05-10 23:47:50
由于fields
或fns
是单元格数组,您必须使用花括号{}
进行索引,以便访问单元格的内容,即字符串。
请注意,您也可以直接在fields
上循环,而不是在数字上循环,这利用了一个整洁的Matlab特性,它允许您循环遍历任何数组。iteration变量采用数组的每一列的值。
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-10 23:41:51
你的fns是一个cellstr数组。您需要使用{}而不是()对其进行索引,才能将单个字符串作为char输出。
fns{i}
teststruct.(fns{i})
使用()对其进行索引将返回一个1长的cellstr数组,该数组与".(name)“动态字段引用所需的char数组的格式不同。格式化,特别是在显示输出中,可能会令人困惑。要查看不同之处,请尝试这个。
name_as_char = 'a'
name_as_cellstr = {'a'}
https://stackoverflow.com/questions/2803962
复制相似问题