adding columes to table and get the names of the columes from an array in matlab

To add columns to a table in MATLAB and get the names of the columns from an array, you can follow these steps:

  1. Create a table using the 'table' command and assign it to a variable name (e.g., 'myTable').
main.m
myTable = table();
19 chars
2 lines
  1. Define an array of column names that you want to add to the table (e.g., 'colNames').
main.m
colNames = {'col1', 'col2', 'col3'};
37 chars
2 lines
  1. Use a 'for' loop to add each column from the array to the table using the 'addvars' function. Note that the first input to 'addvars' should be the table you created in step 1.
main.m
for i = 1:length(colNames)
    myTable = addvars(myTable, zeros(size(myTable, 1), 1), 'Before', 1);
    myTable.Properties.VariableNames{1} = colNames{i};
end
159 chars
5 lines

The above code creates new columns filled with zeros and adds them to the table using the 'Before' option. The 'Before' option specifies the position of the new variable (column) in the table. In this case, it adds the variable before the first column of the table. Finally, the code sets the name of the new column to the corresponding name in the 'colNames' array.

After running the above code, you should have a table 'myTable' with columns named 'col1', 'col2', and 'col3'.

gistlibby LogSnag