Making a matrix square and padding it with desired value in numpy

numpy, python

Solution

Building upon the answer by LucasB here is a function which will pad an arbitrary matrix `M` with a given value `val` so that it becomes square:

def squarify(M,val):
    (a,b)=M.shape
    if a>b:
        padding=((0,0),(0,a-b))
    else:
        padding=((0,b-a),(0,0))
    return numpy.pad(M,padding,mode='constant',constant_values=val)

Problem

In general we could have matrices of arbitrary sizes. For my application it is necessary to have square matrix. Also the dummy entries should have a specified value. I am wondering if there is anything built in numpy? Or the easiest way of doing it EDIT : The matrix X is already there and it is not squared. We want to pad the value to make it square. Pad it with the dummy given value. All the original values will stay the same. Thanks a lot

Original source