MATLAB: How to pre-allocate table rows

performancepreallocatetable

What is the clean way to preallocate rows in a table?
Here is an example to illustrate what I would like:
a = {'a'}
b = 1
a = table( a, b )
a(10,:) = %Some placeholder value to ensure table is extended to be 10 rows
In the example above, the table is trivial, so I could write out the following line. But since the types are known, then MATLAB could in theory just fill this in by itself.
a(10,:) = {{[]}, 0}

Best Answer

Danial, I interpret your question as
"I have a table with one row. I'd need the same table, but lengthened to 10 rows so that I can fill in rows 2-9 without growing it one row at a time."
This actually isn't specific to table, although the fact that tables can hold heterogeneous types makes it a bit more interesting.
(By the way, good on you for knowing to start with {'a'}, and not just 'a'.)
One option is to simply repmat the one-row table to be 10 rows:
>> t = table({'a'},1)
t =
Var1 Var2
____ ____
'a' 1
>> t = repmat(t,10,1)
t =
Var1 Var2
____ ____
'a' 1
'a' 1
'a' 1
'a' 1
'a' 1
'a' 1
'a' 1
'a' 1
'a' 1
'a' 1
If you're filling in the table, it doesn't much matter what's in rows 2-9, since you'll be overwriting them. But if you're a stickler, you can assign to the 11'th row, then delete it:
>> t = table({'a'},1);
>> t(11,:) = t(1,:);
>> t(11,:) = []
t =
Var1 Var2
____ ____
'a' 1
[] 0
[] 0
[] 0
[] 0
[] 0
[] 0
[] 0
[] 0
[] 0
Hope this helps.