开发者

dynamic structure generation in Matlab

I have a list of field names and want to generate a nested struct. I tried this:

fn1 = {'a', 'b', 'c'};
fn2 = {'d', 'e', 'f'};
s = struct();
for n1=fn1
  for n2=fn2
    s.(n1).(n2) = 0 ;
  end
end

but Matlab complaint that the notation ".{fieldname)" is for dynamic structure reference only ("Argument to dynamic structure reference must evaluate 开发者_Python百科to a valid field name.").

I know a solution that works is to loop over the field names, using isfield() and struct(). So how can I achieve this goal without using isfield() and struct(), e.g. by mean of some anonymous function and vectorization? Thanks


Your main problem is that n1 and n2 are cell arrays, which are not valid struct names. Thus, writing

s.(n1{1}).(n2{1}) = 0;

fixes the error.

However, a better method might be to use CELL2STRUCT to create s:

s2 = cell2struct(cell(size(fn2(:))),fn2(:));
s = cell2struct(repmat({s2},size(fn1(:))),fn1(:))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜