MATLAB: How to add variables to a table that are products of other variables

table and matrix operations

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.

Best Answer

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