Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic structure generation in Matlab

Tags:

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 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

like image 931
Martin08 Avatar asked Dec 06 '25 04:12

Martin08


1 Answers

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(:))
like image 106
Jonas Avatar answered Dec 09 '25 15:12

Jonas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!