How to add variables to a table that are products of other variables
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
T4H14
il 10 Ott 2017
Commentato: Walter Roberson
il 11 Ott 2017
If I have a table of 46 variables and I want to add on new variables to this table which are the squares and cubes of some of these variables (columns 10 and 12-18) how can I accomplish this? I would be adding on 16 new variables (columns) in all to the original table.
0 Commenti
Risposta accettata
Walter Roberson
il 10 Ott 2017
cur_varnames = YourTable.Properties.VariableNames;
for K = [10, 12:18]
thisvarname = cur_varnames{K};
thisval = YourTable.(thisvarname);
sq_varname = [thisvarname '_squared'];
cu_varname = [thisvarname '_cubed'];
YourTable.(sq_varname) = thisval .^ 2;
YourTable.(cu_varname) = thisval .^ 3;
end
Più risposte (1)
Andrei Bobrov
il 10 Ott 2017
Modificato: Andrei Bobrov
il 10 Ott 2017
Let T - your table.
ts = reshape(T{:,[10,12:18]}.^reshape(2:3,1,1,[]),size(T,1),[]);
newname = cellstr(reshape(string(T(:,[10,12:18]).Properties.VariableNames)'...
+'_'+["squares","cube"],1,[]));
Tout = [T,array2table(ts,'VariableNames',newname)];
1 Commento
Walter Roberson
il 11 Ott 2017
(Note: the above code requires R2017a or later as it uses some properties of the new string data type)
Vedere anche
Categorie
Scopri di più su Tables in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!