MCPcopy Create free account
hub / github.com/numpy/numpy / diag

Function diag

numpy/lib/twodim_base.py:235–303  ·  view source on GitHub ↗

Extract a diagonal or construct a diagonal array. See the more detailed documentation for ``numpy.diagonal`` if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are usi

(v, k=0)

Source from the content-addressed store, hash-verified

233
234@array_function_dispatch(_diag_dispatcher)
235def diag(v, k=0):
236 """
237 Extract a diagonal or construct a diagonal array.
238
239 See the more detailed documentation for ``numpy.diagonal`` if you use this
240 function to extract a diagonal and wish to write to the resulting array;
241 whether it returns a copy or a view depends on what version of numpy you
242 are using.
243
244 Parameters
245 ----------
246 v : array_like
247 If `v` is a 2-D array, return a copy of its `k`-th diagonal.
248 If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
249 diagonal.
250 k : int, optional
251 Diagonal in question. The default is 0. Use `k>0` for diagonals
252 above the main diagonal, and `k<0` for diagonals below the main
253 diagonal.
254
255 Returns
256 -------
257 out : ndarray
258 The extracted diagonal or constructed diagonal array.
259
260 See Also
261 --------
262 diagonal : Return specified diagonals.
263 diagflat : Create a 2-D array with the flattened input as a diagonal.
264 trace : Sum along diagonals.
265 triu : Upper triangle of an array.
266 tril : Lower triangle of an array.
267
268 Examples
269 --------
270 >>> x = np.arange(9).reshape((3,3))
271 >>> x
272 array([[0, 1, 2],
273 [3, 4, 5],
274 [6, 7, 8]])
275
276 >>> np.diag(x)
277 array([0, 4, 8])
278 >>> np.diag(x, k=1)
279 array([1, 5])
280 >>> np.diag(x, k=-1)
281 array([3, 7])
282
283 >>> np.diag(np.diag(x))
284 array([[0, 0, 0],
285 [0, 4, 0],
286 [0, 0, 8]])
287
288 """
289 v = asanyarray(v)
290 s = v.shape
291 if len(s) == 1:
292 n = s[0]+abs(k)

Callers 5

corrcoefFunction · 0.90
rootsFunction · 0.90
test_vectorMethod · 0.90
test_matrixMethod · 0.90
test_diag_boundsMethod · 0.90

Calls 4

diagonalFunction · 0.90
asanyarrayFunction · 0.85
absFunction · 0.85
zerosFunction · 0.50

Tested by 3

test_vectorMethod · 0.72
test_matrixMethod · 0.72
test_diag_boundsMethod · 0.72