0

How would I pad a matrix with 0's all around? For example, if I have the following matrix:

x x x
x x x
x x x

Then I want

0 0 0 0 0
0 x x x 0
0 x x x 0
0 x x x 0
0 0 0 0 0
Apollo
  • 8,874
  • 32
  • 104
  • 192

2 Answers2

3

The easiest way is to create a second variable of all zeros with the required new size, then to change the inner values.

a= [ 1,2,3;
     4,5,6;
     7,8,9];

 b = zeros(length(a)+2);
 b(2:end-1,2:end-1)=a;

prints

b =

 0     0     0     0     0
 0     1     2     3     0
 0     4     5     6     0
 0     7     8     9     0
 0     0     0     0     0

This will probably be the fastest way, as adding rows and columns to the original array will require more manipulation.

2

TDevlin's answer will work perfectly in the general case, but if you happen to have the Image Processing Toolbox, you can also use padarray:

>> A=magic(3)
A =

   8   1   6
   3   5   7
   4   9   2

>> padarray(A,[1 1])
ans =

   0   0   0   0   0
   0   8   1   6   0
   0   3   5   7   0
   0   4   9   2   0
   0   0   0   0   0
beaker
  • 16,331
  • 3
  • 32
  • 49