mar*_*ovm 32 matlab matlab-struct
我有一个具有许多字段的结构,这些字段是不同长度的向量.我想按顺序访问循环中的字段.我试过getfield如下,但MATLAB不喜欢这样.我怎样才能做到这一点?
S = struct('A', [1 2], 'B',[3 4 5]);
SNames = fieldnames(S);
for loopIndex = 1:2
field = getfield(S, SNames(loopIndex));
%do stuff w/ field
end
??? Index exceeds matrix dimensions
Run Code Online (Sandbox Code Playgroud)
我首先使用结构,因为数组会遇到不同字段长度的问题.还有更好的选择吗?
Mat*_*oug 44
尝试使用动态字段引用,将字符串放在括号中,如定义内容的行所示.
S = struct('A', [1 2], 'B',[3 4 5]);
SNames = fieldnames(S);
for loopIndex = 1:numel(SNames)
stuff = S.(SNames{loopIndex})
end
Run Code Online (Sandbox Code Playgroud)
我同意史蒂夫和亚当的观点.使用细胞.这种语法适合其他情况下的人!
gno*_*ice 16
我想在这里提出三点:
您在上面的代码中出错的原因是您的索引编制方式SNames
.该函数fieldnames
返回字符串的单元格数组,因此您必须使用内容索引(即花括号)来访问字符串值.如果您将代码中的第四行更改为:
field = getfield(S, SNames{loopIndex});
Run Code Online (Sandbox Code Playgroud)
那么你的代码应该没有错误.
正如MatlabDoug所建议的那样,您可以使用动态字段名称来避免使用getfield
(在我看来,这会产生更清晰的代码).
在从亚当建议使用一个单元阵列,而不是结构是正确的标志.这通常是将一系列不同长度的数组收集到单个变量中的最佳方法.您的代码最终会看起来像这样:
S = {[1 2], [3 4 5]}; % Create the cell array
for loopIndex = 1:numel(S) % Loop over the number of cells
array = S{loopIndex}; % Access the contents of each cell
% Do stuff with array
end
Run Code Online (Sandbox Code Playgroud)getfield方法是可以的(虽然我现在没有MATLAB可用,但我不清楚为什么上面的方法不起作用).
对于替代数据结构,您可能还需要查看MATLAB单元阵列.它们还允许您存储和索引不同长度的向量.