How to create identity matrix with numpy

前端 未结 3 2524
走了就别回头了
走了就别回头了 2021-02-20 08:39

How do I create an identity matrix with numpy? Is there a simpler syntax than

numpy.matrix(numpy.identity(n))
相关标签:
3条回答
  • 2021-02-20 09:15

    Also np.eye can be used to create an identity array (In).

    For example,

    >>> np.eye(2, dtype=int)
    array([[1, 0],
           [0, 1]])
    >>> np.eye(3, k=1)
    array([[ 0.,  1.,  0.],
           [ 0.,  0.,  1.],
           [ 0.,  0.,  0.]])
    
    0 讨论(0)
  • 2021-02-20 09:33

    I don't think there is a simpler solution. You can do it slightly more efficiently, though:

    numpy.matrix(numpy.identity(n), copy=False)
    

    This avoids unnecessarily copying the data.

    0 讨论(0)
  • 2021-02-20 09:37

    Here's a simpler syntax:

    np.matlib.identity(n)
    

    And here's an even simpler syntax that runs much faster:

    In [1]: n = 1000
    In [2]: timeit np.matlib.identity(n)
    100 loops, best of 3: 8.78 ms per loop
    In [3]: timeit np.matlib.eye(n)
    1000 loops, best of 3: 695 us per loop
    
    0 讨论(0)
提交回复
热议问题