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', *, like=None)
| 158 | @set_array_function_like_doc |
| 159 | @set_module('numpy') |
| 160 | def eye(N, M=None, k=0, dtype=float, order='C', *, like=None): |
| 161 | """ |
| 162 | Return a 2-D array with ones on the diagonal and zeros elsewhere. |
| 163 | |
| 164 | Parameters |
| 165 | ---------- |
| 166 | N : int |
| 167 | Number of rows in the output. |
| 168 | M : int, optional |
| 169 | Number of columns in the output. If None, defaults to `N`. |
| 170 | k : int, optional |
| 171 | Index of the diagonal: 0 (the default) refers to the main diagonal, |
| 172 | a positive value refers to an upper diagonal, and a negative value |
| 173 | to a lower diagonal. |
| 174 | dtype : data-type, optional |
| 175 | Data-type of the returned array. |
| 176 | order : {'C', 'F'}, optional |
| 177 | Whether the output should be stored in row-major (C-style) or |
| 178 | column-major (Fortran-style) order in memory. |
| 179 | |
| 180 | .. versionadded:: 1.14.0 |
| 181 | ${ARRAY_FUNCTION_LIKE} |
| 182 | |
| 183 | .. versionadded:: 1.20.0 |
| 184 | |
| 185 | Returns |
| 186 | ------- |
| 187 | I : ndarray of shape (N,M) |
| 188 | An array where all elements are equal to zero, except for the `k`-th |
| 189 | diagonal, whose values are equal to one. |
| 190 | |
| 191 | See Also |
| 192 | -------- |
| 193 | identity : (almost) equivalent function |
| 194 | diag : diagonal 2-D array from a 1-D array specified by the user. |
| 195 | |
| 196 | Examples |
| 197 | -------- |
| 198 | >>> np.eye(2, dtype=int) |
| 199 | array([[1, 0], |
| 200 | [0, 1]]) |
| 201 | >>> np.eye(3, k=1) |
| 202 | array([[0., 1., 0.], |
| 203 | [0., 0., 1.], |
| 204 | [0., 0., 0.]]) |
| 205 | |
| 206 | """ |
| 207 | if like is not None: |
| 208 | return _eye_with_like(like, N, M=M, k=k, dtype=dtype, order=order) |
| 209 | if M is None: |
| 210 | M = N |
| 211 | m = zeros((N, M), dtype=dtype, order=order) |
| 212 | if k >= M: |
| 213 | return m |
| 214 | # Ensure M and k are integers, so we don't get any surprise casting |
| 215 | # results in the expressions `M-k` and `M+1` used below. This avoids |
| 216 | # a problem with inputs with type (for example) np.uint64. |
| 217 | M = operator.index(M) |