how to add zeros around a matrix?

14 ビュー (過去 30 日間)
Mucahid Akyar
Mucahid Akyar 2017 年 11 月 22 日
コメント済み: DGM 2024 年 3 月 13 日
for example i have a matrix A = [1 2 3; 2 3 4; 5 6 7] I am working on image processing and I want to add zeros around this matrix like below. How can i do that?
0 0 0 0 0
0 1 2 3 0
0 2 3 4 0
0 5 6 7 0
0 0 0 0 0

採用された回答

Stephen23
Stephen23 2017 年 11 月 22 日
>> conv2(A,[0,0,0;0,1,0;0,0,0])
ans =
0 0 0 0 0
0 1 2 3 0
0 2 3 4 0
0 5 6 7 0
0 0 0 0 0
  5 件のコメント
Stephen23
Stephen23 2017 年 11 月 22 日
編集済み: Stephen23 2017 年 11 月 22 日
It is not clear what you would expect the result to be. MATLAB does not currently have a syntax for looping over two variables at once. You could define the loop to be an index and use that to select elements from those vectors:
iV = 0:1:5;
jV = 0:1:5;
for k = 1:numel(iV)
iN = iV(k);
jN = jV(k);
end
Eren Ozcelik
Eren Ozcelik 2021 年 4 月 30 日
Hi. How can I use this method for non-square matrix? For example creating a border for 1000x1500 matrix.

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

その他の回答 (3 件)

KL
KL 2017 年 11 月 22 日
newA = zeros(size(A)+2);
newA(2:end-1,2:end-1)=A
  1 件のコメント
Medyan
Medyan 2022 年 9 月 16 日
Thx man.

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


Andrei Bobrov
Andrei Bobrov 2017 年 11 月 22 日
編集済み: Andrei Bobrov 2017 年 11 月 22 日
padarray(A,[1 1],0)
  2 件のコメント
Stephen23
Stephen23 2017 年 11 月 22 日
Note: requires the image toolbox.
DGM
DGM 2022 年 7 月 16 日
While padarray() requires IPT, MIMT has padarrayFB(), which uses, but does not require IPT. That's a possibility for those who don't have IPT. ... but then MIMT also has other options for adding borders to images.

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


noam gridish
noam gridish 2024 年 3 月 12 日
% create bigger mat of zeros
[m,n]=size(A);
paded_mat=zeros(m+1,n+1);
paded_mat(2:end-1,2:end-1)=A;
A=paded_mat;
  1 件のコメント
DGM
DGM 2024 年 3 月 13 日
Have you tested this? I ask because it will throw an error. Your preallocated array is too small.

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

Community Treasure Hunt

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

Start Hunting!

Translated by