필터 지우기
필터 지우기

How to pre-allocate table rows

조회 수: 12 (최근 30일)
Daniel Armyr
Daniel Armyr 2016년 2월 8일
댓글: Daniel Armyr 2016년 2월 10일
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}

채택된 답변

Peter Perkins
Peter Perkins 2016년 2월 10일
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.
  댓글 수: 1
Daniel Armyr
Daniel Armyr 2016년 2월 10일
Your second answer is brilliant. One a one-liner, but close enough.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Subhadra Mahanti
Subhadra Mahanti 2016년 2월 8일
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'};

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by