How to add a first row and a first column of zeros in a matrix?

32 ビュー (過去 30 日間)
P_M_Cap
P_M_Cap 2022 年 2 月 14 日
編集済み: Simon Dengler 2022 年 2 月 14 日
hi,
i have a matrix, for example
A=[1 2 3; 4 5 6; 7 8 9]
A = 3×3
1 2 3 4 5 6 7 8 9
how can i add a first row of zeros and a first colum of zeros to reach the following results?
B=[0 0 0 0; 0 1 2 3; 0 4 5 6; 0 7 8 9]
B = 4×4
0 0 0 0 0 1 2 3 0 4 5 6 0 7 8 9
and how can i delete the last row and the last column of a matrix to reach this second results?
C=[0 0 0; 0 1 2; 0 4 5]
C = 3×3
0 0 0 0 1 2 0 4 5
thank you very much matlab users!

採用された回答

Arif Hoq
Arif Hoq 2022 年 2 月 14 日
A=[1 2 3; 4 5 6; 7 8 9];
AA=[zeros(1,3);A];
AAA=zeros(4,1);
B=[AAA AA];
B(:,end)=[];
B(end,:)=[]
B = 3×3
0 0 0 0 1 2 0 4 5

その他の回答 (2 件)

Star Strider
Star Strider 2022 年 2 月 14 日
The easiest way is to create an appropriate zeros matrix and just index into it —
A=[1 2 3; 4 5 6; 7 8 9];
B = zeros(size(A,1)+1,size(A,2)+1);
B(2:end,2:end) = A
B = 4×4
0 0 0 0 0 1 2 3 0 4 5 6 0 7 8 9
C = B(1:end-1,1:end-1)
C = 3×3
0 0 0 0 1 2 0 4 5
Four lines of code to do everything!
.

Simon Dengler
Simon Dengler 2022 年 2 月 14 日
編集済み: Simon Dengler 2022 年 2 月 14 日
bit more general and faster?
A=[1 2 3; 4 5 6; 7 8 9];
A = 3×3
1 2 3 4 5 6 7 8 9
B=zeros(size(A)+1);
B(2:end,2:end)=A
B = 4×4
0 0 0 0 0 1 2 3 0 4 5 6 0 7 8 9

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by