Lucas424
Lucas424

Reputation: 3

How can I pad matrix in python without using the np.pad() function?

I want to take matrix 1 like the one below and pad it with 1 padding so that it looks like matrix 2 or pad it with 2 padding to make it look like matrix 3. I want to do this without using using the np.pad() or any other Numpy function.

Matrix 1

| 4 4 |
| 7 2 |

Matrix 2 - with padding of 1

| 0 0 0 0 |
| 0 4 4 0 |
| 0 7 2 0 |
| 0 0 0 0 |

Matrix 3 - with padding of 2

| 0 0 0 0 0 0 |
| 0 0 0 0 0 0 |
| 0 0 5 1 0 0 |
| 0 0 7 1 0 0 |
| 0 0 0 0 0 0 |
| 0 0 0 0 0 0 |

Upvotes: 0

Views: 759

Answers (1)

Andre
Andre

Reputation: 788

You could create a custom pad function like so:

Very late edit: Do not use this function, use the one below it called pad2().

def pad(mat, padding):
    
    dim1 = len(mat)
    dim2 = len(mat[0])

    # new empty matrix of the required size
    new_mat = [
        [0 for i in range(dim1 + padding*2)]
        for j in range(dim2 + padding*2)
    ]

    # "insert" original matix in the empty matrix
    for i in range(dim1):
        for j in range(dim2):
            new_mat[i+padding][j+padding] = mat[i][j]

    return new_mat

It might not be the optimal/fastest solution, but this should work fine for regular sized matrices.


Very late edit: I tried to use this function on a non square matrix and noticed it threw an IndexError. So for future reference here is the corrected version that works for N x M matrices (where N != M):

def pad2(mat, padding, pad_with=0):
    n_rows = len(mat)
    n_cols = len(mat[0])

    # new empty matrix of the required size
    new_mat = [
        [pad_with for col in range(n_cols + padding * 2)]
        for row in range(n_rows + padding * 2)
    ]

    # "insert" original matix in the empty matrix
    for row in range(n_rows):
        for col in range(n_cols):
            new_mat[row + padding][col + padding] = mat[row][col]

    return new_mat

Upvotes: 1

Related Questions