根据结构名称访问结构字段 [英] access to struct fields based on struct name
本文介绍了根据结构名称访问结构字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在访问MATLAB中的struct的每个字段时遇到问题.我试图将其转换为Cell,但它给了我错误:( 如何通过2个循环访问每个字段? 我写了以下代码:
I have problem to access each field of struct in MATLAB. I tried to convert it to Cell however, it give me error :( How can I access each field with 2 loops ? I have wrote following code :
a=load(goalMFile);
struct_name=fieldnames(a);
struct_cell=struct2cell(a);
cellsz = cellfun(@size,struct_cell,'uni',false);
ans=cellsz{:};
row=ans(1);
col=ans(2);
for counter1=1:row
for counter2=1:col
a.struct_name{(counter1-1)*counter2+counter2} % the error is Here
end
end
如果有人能帮助我,我将非常感激.
I will really appreciate, If anyone could help me.
推荐答案
您可以使用s.(fname)
动态访问结构,其中fname
是char变量.注意fname
周围的( )
.
You can access a structure dynamically with s.(fname)
where fname
is char variable. Note the ( )
around fname
.
一个例子将阐明:
% Example structure
s.A = 10;
s.B = 20;
% Retrieve fieldnames
fnames = fieldnames(s);
% Loop with numeric index
for ii = 1:numel(fnames)
s.(fnames{ii})
end
% ...or loop by fieldname directly
for f = fnames'
s.(f{:})
end
这篇关于根据结构名称访问结构字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文