Initialize an identity matrix for matrix operations.
Linear algebra
NumPy · Function
Creates an n-by-n identity array: ones on the main diagonal and zeros elsewhere. The optional dtype selects the output type, while like can enable compatible non-NumPy array creation.
Call numpy.identity with the desired dimension and optionally a data type. It constructs a square array whose diagonal entries are one and whose remaining entries are zero; unless specified, the output uses floating-point values.
numpy.identity(n, dtype=None, *, like=None)| Name | Type | Description |
|---|---|---|
n | int | Number of rows and columns in the n × n output. |
dtype | data-type, optional | Data type of the output; defaults to float. |
like | array_like, optional | Reference object that can allow creation of a non-NumPy array. |
out: ndarray — an n × n array with its main diagonal set to one and every other element set to zero.
dtype to choose the type stored by the returned array.dtype is omitted, the array elements are floating-point values rather than integers.like argument can delegate array creation to a compatible non-NumPy array implementation.import numpy as np
identity = np.identity(3, dtype=np.int64)
print(identity)
Creates a 3-by-3 integer identity array with ones on the main diagonal and zeros elsewhere.
Linear algebra
Testing
Typed numerical data
numpy.identity return?It creates an n-by-n square array with ones on the main diagonal and zeros elsewhere. The default output data type is float unless dtype is provided.
Follow-up: How would you obtain integer entries? Pass an integer data type, such as dtype=np.int64.
n and dtype parameters control?n specifies both the number of rows and the number of columns, so the result is always square. dtype controls the output element type and is optional.
Follow-up: What happens when n is 3 and dtype is omitted? A 3-by-3 array of floating-point zeros and ones is returned.
like?like is an optional reference object that can enable creation of an array that is not a NumPy array. If that object supports __array_function__, it determines the result and can make it compatible with the reference.
Follow-up: Why use like instead of relying on NumPy's default? Use it when an alternative array implementation needs to participate in array creation.
numpy.eyenumpy.diagnumpy.ones