如何动态访问结构字段? [英] How do I access structure fields dynamically?
问题描述
我有一个结构,其中包含许多字段,这些字段是不同长度的向量.我想按顺序访问循环中的字段.我尝试了如下的getfield,但是MATLAB不喜欢这样.我怎样才能做到这一点?
I have a structure with many fields which are vectors of different lengths. I would like to access the fields within a loop, in order. I tried getfield as follows but MATLAB doesn't like that. How can I do this?
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
我首先使用结构,因为数组在使用不同的字段长度时会遇到麻烦.有更好的替代方法吗?
I'm using structures in the first place because an array would have trouble with the different field lengths. Is there a better alternative to that?
推荐答案
尝试使用动态字段引用,在其中将字符串放在括号中,如在定义 stuff 的行上所示.
Try dynamic field reference where you put a string in the parenthesis as seen on the line defining stuff.
S = struct('A', [1 2], 'B',[3 4 5]);
SNames = fieldnames(S);
for loopIndex = 1:numel(SNames)
stuff = S.(SNames{loopIndex})
end
我同意史蒂夫和亚当的观点.使用细胞.但是,此语法适合其他情况下的人!
I concur with Steve and Adam. Use cells. This syntax is right for people in other situations though!
这篇关于如何动态访问结构字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!