# how to add zeros around a matrix?

21 views (last 30 days)
Mucahid Akyar on 22 Nov 2017
Commented: DGM on 13 Mar 2024
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 on 22 Nov 2017
>> 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
Stephen23 on 22 Nov 2017
Edited: Stephen23 on 22 Nov 2017
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 on 30 Apr 2021
Hi. How can I use this method for non-square matrix? For example creating a border for 1000x1500 matrix.

KL on 22 Nov 2017
newA = zeros(size(A)+2);
newA(2:end-1,2:end-1)=A
Medyan on 16 Sep 2022
Thx man.

Andrei Bobrov on 22 Nov 2017
Edited: Andrei Bobrov on 22 Nov 2017
Stephen23 on 22 Nov 2017
Note: requires the image toolbox.
DGM on 16 Jul 2022
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 on 12 Mar 2024
% create bigger mat of zeros
[m,n]=size(A);
DGM on 13 Mar 2024
Have you tested this? I ask because it will throw an error. Your preallocated array is too small.