Dynamically naming new table columns in a loop

조회 수: 19 (최근 30일)
Lisa Lafleur
Lisa Lafleur 2021년 12월 17일
댓글: Lisa Lafleur 2021년 12월 18일
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
Lisa Lafleur
Lisa Lafleur 2021년 12월 17일
I just noticed the left notation is wrong. The 'summaryTable' should be inside the name like
eval(strcat('summaryTable.Multiplied', string(i)))

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2021년 12월 17일
편집: Stephen23 2021년 12월 17일
"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
Lisa Lafleur
Lisa Lafleur 2021년 12월 18일
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!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Voss
Voss 2021년 12월 17일
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

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by