Michiel Karrenbelt
Michiel Karrenbelt

Reputation: 143

dynamic variable names in matlab

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.

Upvotes: 1

Views: 400

Answers (1)

TroyHaskin
TroyHaskin

Reputation: 8401

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

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

Upvotes: 6

Related Questions