1

Suppose I have a matrix [1 2;3 4], but I need [0 0 0 0;0 1 2 0;0 3 4 0;0 0 0 0], I now how to do it, but is there a function can solve it within one line?

Yunfei Lu
  • 389
  • 1
  • 5
  • 18

1 Answers1

2

If you have the image processing toolbox, use padarray:

>> A = [1 2; 3 4];
>> B = padarray(A, [1 1])

B =

     0     0     0     0
     0     1     2     0
     0     3     4     0
     0     0     0     0

The first input is the matrix you want to pad, and the second input is how many zeroes along the border in each dimension you want to see. You want a 1 element zero border both horizontally and vertically, and so [1 1] is what is required.

However, I'm confused as to why you want this to be in "one-line". If you want a one element border surrounding the original matrix, what's wrong with having multiple lines?

A = [1 2; 3 4];
B = zeros(size(A) + 2);
B(2:end-1,2:end-1) = A;

This is three lines of code, including the definition of your original matrix, but each line is quite clear. You define a new matrix that has 2 more rows and 2 more columns that the original, because you want a 1 element zero boundary around the original matrix, then just place it in the middle.

rayryeng
  • 102,964
  • 22
  • 184
  • 193