Dynamically naming new table columns in a loop

19 views (last 30 days)
I'm inputting large data sets (~300 x 500) and need to act on the data creating lots of new variables. I've got syntax for adding, deleting, moving columns but can't find anything that talks about how to assign values to a column being created in the same line. There are so many columns that need to be acted on in the same way I really need loops. The closest seems to be incorporating eval, but it's not doing what I expect. As a simplified example:
summaryTable = readtable(strcat(path,'/',name,ext)); %import big csv file
%the imported column names are ["VarA1"; "VarA2"; "VarB1"; "VarB2"]
for i = 1:2
eval(strcat(summaryTable, '.Multiplied', string(i))) = eval(strcat('summaryTable.VarA', string(i))) .* eval(strcat('summaryTable.VarB', string(i)))
end
The eval statements work on the right, but assigning the new variable doesn't. What's the secret?
  1 Comment
Lisa Lafleur
Lisa Lafleur on 17 Dec 2021
I just noticed the left notation is wrong. The 'summaryTable' should be inside the name like
eval(strcat('summaryTable.Multiplied', string(i)))

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 17 Dec 2021
Edited: Stephen23 on 17 Dec 2021
"What's the secret?"
Very simple: don't use EVAL.
It is simpler, much more robust, and much more efficient to add fields using the syntaxes given in the documentation:
For example:
T = readtable(..)
for k = 1:2
F0 = "Mult"+k;
F1 = "VarA"+k;
F2 = "VarB"+k;
T.(F0) = T.(F1) .* T.(F2);
end
  1 Comment
Lisa Lafleur
Lisa Lafleur on 18 Dec 2021
Ahh, the evil eval statement. I wasn't famliar with the
T.(F0) =
notation. This means I need to add a line in my loops to dynamically define my new column name as a string, then I can add it to the table via assigning things to it with the T.(newName) notation. Not a huge deal.
Thanks!

Sign in to comment.

More Answers (1)

Voss
Voss on 17 Dec 2021
Use dynamic field names (the documentation is for structs, but it works for tables too (evidently)):
VarA1 = [1 2 3].';
VarA2 = [1 2 3].'+3;
VarB1 = [1 2 3].'+6;
VarB2 = [1 2 3].'+9;
summaryTable = table(VarA1,VarA2,VarB1,VarB2);
display(summaryTable);
summaryTable = 3×4 table
VarA1 VarA2 VarB1 VarB2 _____ _____ _____ _____ 1 4 7 10 2 5 8 11 3 6 9 12
for i = [1 2]
str = num2str(i);
summaryTable.(['Multiplied' str]) = summaryTable.(['VarA' str]) .* summaryTable.(['VarB' str]);
end
display(summaryTable);
summaryTable = 3×6 table
VarA1 VarA2 VarB1 VarB2 Multiplied1 Multiplied2 _____ _____ _____ _____ ___________ ___________ 1 4 7 10 7 40 2 5 8 11 16 55 3 6 9 12 27 72

Categories

Find more on Structures in Help Center and File Exchange

Tags

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!