MATLAB Answers

How do I define an empty table of unknown size?

6 views (last 30 days)
Hi,
I want to define an empty table to fill in a for loop. The size of the table is defined by another variable. How do I define the "VariableType" variable without knowing how many variables there are? In my case they will all be strings. Example:
T = table('Size', [2, numel(Elements)], 'VariableType',["string","string","string","string","string"]);
In this particular cae, numel(Elements) would be 5. But how do I define the table if I don't know numel(Elements) ?

  0 Comments

Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 26 May 2020
Elements = 1:5;
n = numel(Elements);
T = table('Size', [2 n], 'VariableTypes', repmat("string", 1, n))

More Answers (1)

Walter Roberson
Walter Roberson on 26 May 2020
Sorry, variables that do not exist do not have any datatype.
As you add variables to the table, the datatype associated with the variable will be the determined by the datatype of the value being assigned. If necessary, string() the value you are assigning into the table.

  3 Comments

Fabrice Lambert
Fabrice Lambert on 26 May 2020
T = table('Size', [2, numel(Elements)])
Error using table (line 284)
Specify variable types when creating a table with a specified size.
You have to define the Variable Type when you specifiy the size...
Walter Roberson
Walter Roberson on 26 May 2020
That is not an empty table with an unknown number of variables: that is a table with 2 rows and a known number of variables.
Fabrice Lambert
Fabrice Lambert on 26 May 2020
In the example I gave, the number of variables is known for clearness' sake, yes. In practice "Elements" can be of variable length, so I need code that avoids fixed numbers of variables.

Sign in to comment.

Products


Release

R2020a

Translated by