Dynamic structure in Matlab

I have a list of field names and you want to create a nested structure. 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 complains that the designation ".namename" "refers only to the dynamic structure" ("The argument to reference the dynamic structure must be evaluated using a valid field name.").

I know that a solution that works is to iterate over the field names using isfield () and struct (). So how can I achieve this without using isfield () and struct (), for example. through some anonymous function and vectorization? Thanks

+3
source share
1 answer

, n1 n2 , . ,

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

.

CELL2STRUCT s:

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

All Articles