how can I add zeros elements to a matrix?

182 ビュー (過去 30 日間)
moein Pakdel sefidi
moein Pakdel sefidi 2015 年 6 月 18 日
コメント済み: David Buzzell 2020 年 9 月 28 日
I have a matrix a: a= [1 2 3; 1 2 3; 1 2 3] I want to add zero rows and cols and convert it to b:
b=
1 2 3 0 0
1 2 3 0 0
1 2 3 0 0
0 0 0 0 0
0 0 0 0 0
how is it possible?
(size of 'a' can be different, in fact it's a matrix which shows image m*n)

採用された回答

Salaheddin Hosseinzadeh
Salaheddin Hosseinzadeh 2015 年 6 月 18 日
編集済み: Salaheddin Hosseinzadeh 2015 年 6 月 18 日
Hi Moein,
there are different ways to do this. One of which is to define a fully zero matrix with all zeros
newMatrix = zeros(5,5); % all zero matrix
Then assign the non zero elements.
newMatrix(1:3,1:3) = oldMatrix; % oldMatrix is a, newMatrix is b
This is one way to do it.
Another way would be to concatenate the oldMatrix with zeros.
neMatrix_1 = [oldMatrix,zeros(3,2)]; % horizontal concatenation
newMatrix_2 = [newMatrix_1;zeros(2,5)]; % vertical concatenation
This should give you the same in newMatrix_2
  1 件のコメント
moein Pakdel sefidi
moein Pakdel sefidi 2015 年 6 月 18 日
thanks Salaheddin.

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

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2015 年 6 月 18 日
a= [1 2 3; 1 2 3; 1 2 3]
b = a
b(5,5) = 0

Ugur Aygun
Ugur Aygun 2016 年 10 月 26 日
Hi Moein,
Easiest way to do this is to use padarray command.
a= [1 2 3; 1 2 3; 1 2 3];
padarray(a,[2,2],0,'post')
ans =
1 2 3 0 0
1 2 3 0 0
1 2 3 0 0
0 0 0 0 0
0 0 0 0 0
Here [2,2] indicates how many terms you will add to rows and columns respectively.
  1 件のコメント
David Buzzell
David Buzzell 2020 年 9 月 28 日
This requires the Image Processing Toolbox

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by