Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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

like image 775
Shan Avatar asked Jun 03 '12 14:06

Shan


1 Answers

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)
like image 113
yannis Avatar answered Nov 15 '22 13:11

yannis