Home > front end >  How to use numpy.eye function with custom diagonal values?
How to use numpy.eye function with custom diagonal values?

Time:08-12

I am trying to use a single line of code to make a matrix with zeros except a custom value for the diagonals. I am able to do it like the code I put below, but am wondering if I can do it by only using np.eye?

import numpy as np
a = np.eye(4,4 k=0)  
np.fill_diagonal (a,4)

print(a)

CodePudding user response:

try the identity matrix in numpy module:

a=np.identity(10)*4

CodePudding user response:

import numpy as np

a = np.eye(4)*4

print(a)

CodePudding user response:

I would avoid np.eye() altogether and just use np.fill_diagonal() on a zeroed matrix, if you are not using any of its features:

import numpy as np


def value_eye_fill(value, n):
    result = np.zeros((n, n))
    np.fill_diagonal(result, value)
    return result

That should be the fastest approach for larger inputs, within NumPy.

  • Related