Dynamically naming new table columns in a loop
Mostra commenti meno recenti
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 Commento
Lisa Lafleur
il 17 Dic 2021
Risposta accettata
Più risposte (1)
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);
for i = [1 2]
str = num2str(i);
summaryTable.(['Multiplied' str]) = summaryTable.(['VarA' str]) .* summaryTable.(['VarB' str]);
end
display(summaryTable);
1 Commento
Link to the correct documentation (for tables, not structs):
Categorie
Scopri di più su Structures in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!