3

When I am trying to create a table using the following code:

sz = [4 3];
varTypes = ["double","datetime","string"];
varNames = ["Temperature","Time","Station"];
temps = table('Size',sz,'VariableTypes',varTypes,'VariableNames',varNames)

I get:

Error using table (line 254) Specify variable types as a cell array of character 
vectors, indicating the type of each variable to be created.

Please help me to find what I am missing here. I am using MATLAB R2018a.

HforHisham
  • 1,914
  • 1
  • 22
  • 34
  • It works for me as it is; have you tried using cell arrays as in the documentation, i.e., `{'double','datetime','string'}`, etc. – kikon Oct 05 '22 at 03:03
  • This does not work also for me. – HforHisham Oct 05 '22 at 03:05
  • I don't know why; it's almost identical with the example in the [documentation](https://nl.mathworks.com/help/matlab/ref/table.html), `openExample('matlab/SpecifySizeAndVariableTypesExample')`. I actually tested your code online with "Try This Example" – kikon Oct 05 '22 at 03:09
  • 2
    You should read the 2018a docs; type `doc table` in your MATLAB command window to open those. The version history shows changes in every single release from 2019b up to and including 2022a. You might be using "new" syntax which hasn't been added for 2018a – Adriaan Oct 05 '22 at 07:39

2 Answers2

2

The error message indicates that you need to use single-quote char vectors for that syntax. (There were some rough edges regarding table creation and double-quote strings...). You can use cellstr to work around this in R2018a, like so:

sz = [4 3];
varTypes = ["double","datetime","string"];
varNames = ["Temperature","Time","Station"];
temps = table('Size',sz,'VariableTypes',cellstr(varTypes),...
    'VariableNames',cellstr(varNames))
Edric
  • 23,676
  • 2
  • 38
  • 40
1

The ability to use the 'Size' input was brand new for 18a, in case you're hitting a bug and/or want a solution which will run on older versions of MATLAB, you could use a custom function which populates an empty table according to whatever defaults you want. More variable types could be added to this demo:

>> temps = emptyTable( 4, varTypes, varNames )
temps =
  4×3 table
    Temperature    Time    Station
    ___________    ____    _______
    NaN            NaT     ""     
    NaN            NaT     ""     
    NaN            NaT     ""     
    NaN            NaT     ""  

This is the function:

function tbl = emptyTable( nRows, varTypes, varNames )
    tbl = table();
    varTypes = cellstr(varTypes); % hande string/char/cellstr input
    for ii = 1:numel(varTypes)
        varName = varNames{ii};
        switch varTypes{ii}
            case 'double'
                tbl.(varName) = NaN(nRows,1);
            case 'datetime'
                tbl.(varName) = NaT(nRows,1);
            case 'string'
                tbl.(varName) = repmat("",nRows,1);
        end
    end
end
Wolfie
  • 27,562
  • 7
  • 28
  • 55