Home > database >  Create an empty table in MATLAB
Create an empty table in MATLAB

Time:10-06

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.

CodePudding user response:

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))

CodePudding user response:

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
  • Related