dynamic variable names in matlab

2019-08-09 04:04发布

问题:

I wish to expand a structure (bac) with a number of fields from another structure (BT). The names of these fields are contained in the cell array (adds) as strings.

this is what i have now (and obviously doesn't do the job, explaining this post):

for i=1:numel(adds)
    eval(genvarname('bac.',adds{i})) = eval(strcat('BT.',adds{i}));
end

I also tried using sprintf, which did not seem to work for me. I feel confident one of you knows how to do it, since I feel it should be rather easy.

回答1:

The best way of doing this is to use dynamic field names:

for i=1:numel(adds)
    bac.(adds{i}) = BT.(adds{i});
end