Moussekim
Moussekim

Reputation: 97

Extend the borders of a matrix and replicate the border elements in MATLAB

I am given the following matrix B:

B = 

1  4  7
2  5  8
3  6  9

I would like to pad this matrix so that there is a 1 element border that surrounds it with the border elements replicated. Essentially, I would like this result:

B =                 
    1   1   4   7   7
    1   1   4   7   7
    2   2   5   8   8
    3   3   6   9   9
    3   3   6   9   9

How can I do this in MATLAB?

Upvotes: 2

Views: 1544

Answers (2)

Schlacki
Schlacki

Reputation: 193

The question was explicitly to add a single element as border, so try this (no toolbox needed):

B = [1 4 7; 2 5 8; 3 6 9] % or use  B=rand(3,4), etc. to try something else.
B2 = B([1 1:end end],[1 1:end end])

This is the result (as desired):

B =
    1   4   7
    2   5   8
    3   6   9
B2 =
    1   1   4   7   7
    1   1   4   7   7
    2   2   5   8   8
    3   3   6   9   9
    3   3   6   9   9

Upvotes: 1

rayryeng
rayryeng

Reputation: 104545

If you have the Image Processing Toolbox, use padarray, specifically the replicate flag. If you don't have it, there's an implementation that someone made here on Github: https://github.com/gpeyre/matlab-toolboxes/blob/master/toolbox_nlmeans/toolbox/ordfilt2/padarray.m . You can download it and use the function for your own use.

padarray creates a larger matrix with the source matrix centred within this larger matrix. You have several options on what you can do with the extra border elements. The default behaviour is to set these equal to 0. However, we can specify the replicate flag, which copies values along the original border of the matrix and places them along the extra border elements with this new matrix. Because you want to go from 3 x 3 to 5 x 5, you just need a 1 element border along both dimensions. You specify this with the second parameter to padarray. The replicate flag is the third parameter:

>> B = reshape(1:9, 3, 3);
>> B2 = padarray(B, [1 1], 'replicate')

B2 =

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

Edit

If you don't want to use padarray, you can use the scatteredInterpolant class instead, with nearest as the interpolation flag. You would build a 3 x 3 2D spatial grid of coordinates that map to each value in B, then we'd specify a 5 x 5 spatial grid of coordinates where the border elements are outside of the range of the original 3 x 3 grid. Something like this:

>> [X,Y] = meshgrid(1:3,1:3);
>> [X2,Y2] = meshgrid(0:4,0:4);
>> F = scatteredInterpolant(X(:),Y(:),B(:),'nearest');
>> B2 = F(X2, Y2)

B2 =

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

Upvotes: 4

Related Questions