shift matrix from a specific row

16 ビュー (過去 30 日間)
negin tebyani
negin tebyani 2018 年 2 月 9 日
コメント済み: KL 2018 年 2 月 9 日
I have a matrix that I need to shift some rows according to a special number i, for example if i=3 I have to shift all rows from row 3 down because I have to add new elements to that row, so I should shift all the rows after this one (rows 1 and 2 have to stay the same.) for doing this I added a new row to my matrix with all elements of zero, and now I have to shift this row of zeros (which is the last row) to the i'th row. for example:
i=3
a=[1,2,3;4,5,6;7,8,9,10,11,12]
and I want to add b=[8,8,8] to the third row, so rows: 7,8,9 and 10,11,12 have to shift down. after adding row of zeros:
a=[1,2,3;4,5,6;7,8,9,10,11,12;0,0,0]
and then row 0,0,0 should be shifted to the third row which is 7,8,9 and row 7,8,9 should shift to 4th row and so on.. how can I do this in matlab?

採用された回答

Geoff Hayes
Geoff Hayes 2018 年 2 月 9 日
negin - if you want to insert b as the third row of a then you could just do
a = [1,2,3;4,5,6;7,8,9;10,11,12];
b = [8 8 8];
a = [a(1:2,:) ; b ; a(3:end,:)];
In the above, we just concatenate the first two rows of a (that is, a(1:2,:)) with b and then with the remaining rows of a to get
a =
1 2 3
4 5 6
8 8 8
7 8 9
10 11 12
  1 件のコメント
negin tebyani
negin tebyani 2018 年 2 月 9 日
thanks

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

その他の回答 (1 件)

KL
KL 2018 年 2 月 9 日
Pretty much the same answer as Geoff Hayes' but just with a handle,
add_row = @(ind,a) [a(1:ind-1,:); zeros(1,size(a,2)); a(ind:end,:)];
ind=3
a=[1,2,3;4,5,6;7,8,9;10,11,12]
b = add_row(ind,a)
  2 件のコメント
negin tebyani
negin tebyani 2018 年 2 月 9 日
thank you for the answer
KL
KL 2018 年 2 月 9 日
You're very welcome!

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by