Add rows to table, not append

3 ビュー (過去 30 日間)
Emily Doherty
Emily Doherty 2021 年 12 月 19 日
コメント済み: Siddharth Bhutiya 2022 年 1 月 5 日
I have a table and need to add rows to it, but I do not want to append them to the end of the table. For instance, I have a table with 5 rows and I need to add a row, but I need the new row to be the 2nd row and all the successive rows to move down one.

回答 (1 件)

Star Strider
Star Strider 2021 年 12 月 19 日
One approach is to duplicate the table by first moving everything from the second row to the end down one, then inserting the new row into it —
T1 = array2table(randi(9 ,10, 3))
T1 = 10×3 table
Var1 Var2 Var3 ____ ____ ____ 2 7 6 5 1 1 3 2 6 8 3 8 2 2 9 2 4 5 2 9 7 3 5 3 6 2 8 5 2 2
newRow = randi([10 19], 1, 3)
newRow = 1×3
10 12 11
T1{3:end+1,:} = T1{2:end,:}; % Expand Table Row Length
T1{2,:} = newRow % Insert New Row To Create Desired REsult
T1 = 11×3 table
Var1 Var2 Var3 ____ ____ ____ 2 7 6 10 12 11 5 1 1 3 2 6 8 3 8 2 2 9 2 4 5 2 9 7 3 5 3 6 2 8 5 2 2
.
  1 件のコメント
Siddharth Bhutiya
Siddharth Bhutiya 2022 年 1 月 5 日
Another way to do it would be to use vertcat.
>> T1 = array2table(randi(9 ,10, 3))
T1 =
10×3 table
Var1 Var2 Var3
____ ____ ____
7 4 3
1 4 7
3 7 6
1 8 2
1 2 2
8 5 5
7 5 9
3 6 4
9 7 6
1 7 3
>> i = 2; % Insert a new second row
>> data = {10 12 11}; % new data for the second row
>> T1 = [T1(1:i-1,:); data; T1(i:end,:)]
T1 =
11×3 table
Var1 Var2 Var3
____ ____ ____
7 4 3
10 12 11
1 4 7
3 7 6
1 8 2
1 2 2
8 5 5
7 5 9
3 6 4
9 7 6
1 7 3

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeTables についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by