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

Time:12-01

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 |

CodePudding user response:

You could create a custom pad function like so:

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.

  • Related