Search code examples
arraysmatlabcellvariable-types

Convert cell of strings into column of table in MATLAB


I try to use a vector as a column in a table (in MATLAB). However, I always get different errors. Below is a reproducible example, together with the recieved errors:

% What I have:
my_table = array2table(NaN(5, 3));
my_table.Properties.VariableNames = {'col_1' 'col_2' 'col_3'};
my_cell = {'a', 'b', 'c', 'd', 'e'};

% What I tried:
my_table.col_3 = my_cell; %Error: To assign to or create a variable in a table, the number of rows must match the height of the table.
my_table.col_3(1:5) = my_cell; %Error: Conversion to double from cell is not possible.
my_table.col_3.Properties.VariableTypes = {'string'}; %Error: Unable to perform assignment because dot indexing is not supported for variables of this type.

How can I solve this task?


Solution

  • If you want to keep the cell type you could use:

    my_table.col_3 = my_cell.'
    

    Advantage: You can store more than one character in each row.

    Why my_table.col_3 = my_cell doesn't work:

    %size(my_table.col_3) = 5x1
    %                       ↕ ↕
    %size(my_cell)        = 1x5
    

    As you can see above, the size of the first dimension of your cell array does not match with the size of the first dimension of you table. So you can simply permute the dimension of your cell with .'

    So now:

    %size(my_table.col_3) = 5x1
    %                       ↕ ↕
    %size(my_cell.')      = 5x1
    

    And matlab (and you) is/are happy.