Schnigges
Schnigges

Reputation: 1326

Best way to implement matrix padding

I'm trying to pad a matrix filled with zeros at the borders with the values at the pixel which is closest to the border, for example:

A = rand(5);
Z = zeros(9);
Z(3:7, 3:7) = A;

enter image description here

Now I'd like to complete the matrix borders in the following way:

enter image description here

I'm looking for a nice solution without any for-loops

EDIT:

It should look like this:

enter image description here

Upvotes: 0

Views: 1385

Answers (2)

Phonon
Phonon

Reputation: 12737

% Create a random image
I = round(rand(8)*70);

% Number of pixels to pad on each side
padSize = 3;

% Create a resulting image matric
sizeY = size(I,1);
sizeX = size(I,2);

J = zeros( sizeY + padSize*2, sizeX + padSize*2 );

% Fill in the original
J( (padSize+1):(padSize+sizeY) , (padSize+1):(padSize+sizeX) ) = I;

% Fill in areas above, below and to the sides or original
%top
J( 1:padSize, (padSize+1):(padSize+sizeX) ) = repmat(I(1,:),padSize,1);
%bottom
J( (padSize+sizeX+1):end, (padSize+1):(padSize+sizeX) ) = repmat(I(end,:),padSize,1);
%left
J( (padSize+1):(padSize+sizeY), 1:padSize ) = repmat(I(:,1),1,padSize);
%right
J( (padSize+1):(padSize+sizeY), (padSize+sizeY+1):end ) = repmat(I(:,end),1,padSize);

% Fill in the corners
J(1:padSize, 1:padSize)                         = I(1,1);
J((padSize+sizeY+1):end, 1:padSize)             = I(end,1);
J(1:padSize, (padSize+sizeX+1):end)             = I(1,end);
J((padSize+sizeY+1):end, (padSize+sizeX+1):end) = I(end,end);

Upvotes: 1

chappjc
chappjc

Reputation: 30579

You want padarray with the 'replicate' option. For example to replicate 2x2 borders on all sides,

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

Upvotes: 5

Related Questions