How to pre-allocate table rows
6 views (last 30 days)
Show older comments
Daniel Armyr
on 8 Feb 2016
Commented: Daniel Armyr
on 10 Feb 2016
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}
0 Comments
Accepted Answer
Peter Perkins
on 10 Feb 2016
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.
More Answers (1)
Subhadra Mahanti
on 8 Feb 2016
I can think of several ways to do it depending on your data. One way would be: create a cell array of row x column and covert that to a table
data=cell(5,3);
myTable = cell2table(data);
% You can alwayschange the variable names of the table later
myTable.Properties.VariableNames = {'Col1', 'Col2', 'Col3'};
myTable.Properties.RowNames = {'Row1', 'Row2', 'Row3','Row4','Row5'};
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!