Return a 2-D array with ones on the diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the output. M : int, optional Number of columns in the output. If None, defaults to `N`. k : int, optional Index of the diagonal: 0 (the defau
(N, M=None, k=0, dtype=float, order='C', *, device=None, like=None)
| 178 | @finalize_array_function_like |
| 179 | @set_module('numpy') |
| 180 | def eye(N, M=None, k=0, dtype=float, order='C', *, device=None, like=None): |
| 181 | """ |
| 182 | Return a 2-D array with ones on the diagonal and zeros elsewhere. |
| 183 | |
| 184 | Parameters |
| 185 | ---------- |
| 186 | N : int |
| 187 | Number of rows in the output. |
| 188 | M : int, optional |
| 189 | Number of columns in the output. If None, defaults to `N`. |
| 190 | k : int, optional |
| 191 | Index of the diagonal: 0 (the default) refers to the main diagonal, |
| 192 | a positive value refers to an upper diagonal, and a negative value |
| 193 | to a lower diagonal. |
| 194 | dtype : data-type, optional |
| 195 | Data-type of the returned array. |
| 196 | order : {'C', 'F'}, optional |
| 197 | Whether the output should be stored in row-major (C-style) or |
| 198 | column-major (Fortran-style) order in memory. |
| 199 | device : str, optional |
| 200 | The device on which to place the created array. Default: None. |
| 201 | For Array-API interoperability only, so must be ``"cpu"`` if passed. |
| 202 | |
| 203 | .. versionadded:: 2.0.0 |
| 204 | ${ARRAY_FUNCTION_LIKE} |
| 205 | |
| 206 | .. versionadded:: 1.20.0 |
| 207 | |
| 208 | Returns |
| 209 | ------- |
| 210 | I : ndarray of shape (N,M) |
| 211 | An array where all elements are equal to zero, except for the `k`-th |
| 212 | diagonal, whose values are equal to one. |
| 213 | |
| 214 | See Also |
| 215 | -------- |
| 216 | identity : (almost) equivalent function |
| 217 | diag : diagonal 2-D array from a 1-D array specified by the user. |
| 218 | |
| 219 | Examples |
| 220 | -------- |
| 221 | >>> import numpy as np |
| 222 | >>> np.eye(2, dtype=np.int_) |
| 223 | array([[1, 0], |
| 224 | [0, 1]]) |
| 225 | >>> np.eye(3, k=1) |
| 226 | array([[0., 1., 0.], |
| 227 | [0., 0., 1.], |
| 228 | [0., 0., 0.]]) |
| 229 | |
| 230 | """ |
| 231 | if like is not None: |
| 232 | return _eye_with_like( |
| 233 | like, N, M=M, k=k, dtype=dtype, order=order, device=device |
| 234 | ) |
| 235 | if M is None: |
| 236 | M = N |
| 237 | m = zeros((N, M), dtype=dtype, order=order, device=device) |