gpt4 book ai didi

matlab - 在 MATLAB 中迭代结构字段名

转载 作者:太空宇宙 更新时间:2023-11-03 19:05:18 25 4
gpt4 key购买 nike

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

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'

我无法理解它。

最佳答案

您必须使用大括号 ({}) 访问 字段,因为 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

关于matlab - 在 MATLAB 中迭代结构字段名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2803962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com