Skip to content

Commit b636b8a

Browse files
authored
Added documentation entry for NumPy ndarray trace() method (#7830)
* Added documentation entry for NumPy ndarray trace() method * Enhance .trace() method documentation for clarity Clarified explanation of the .trace() method for NumPy arrays, including details on handling multi-dimensional arrays and optional parameters. * Correct syntax for numpy.trace to ndarray.trace Updated the syntax for the numpy trace function to reflect the correct usage with ndarray. * Update trace.md ---------
1 parent 5f95019 commit b636b8a

File tree

1 file changed

+89
-0
lines changed
  • content/numpy/concepts/ndarray/terms/trace

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
---
2+
Title: '.trace()'
3+
Description: 'Returns the sum of the elements along the diagonal of an array.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Arrays'
9+
- 'Linear Algebra'
10+
- 'Matrices'
11+
- 'NumPy'
12+
- 'Python'
13+
CatalogContent:
14+
- 'learn-python-3'
15+
- 'paths/data-science'
16+
---
17+
18+
The **`.trace()`** method returns the sum of the elements along the diagonal of a [NumPy](https://www.codecademy.com/resources/docs/numpy) array. For 2D arrays, the diagonal consists of elements where the row index equals the column index. For multi-dimensional arrays, the axes specified by axis1 and axis2 define the matrix dimensions for diagonal summation.
19+
20+
The `.trace()` method supports optional parameters to select a diagonal offset or specify axes, making it versatile for arrays of different shapes and orientations.
21+
22+
## Syntax
23+
24+
```pseudo
25+
ndarray.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
26+
```
27+
28+
**Parameters:**
29+
30+
- `offset` (Optional): The diagonal offset from the main diagonal. A positive value selects a diagonal above the main diagonal, while a negative value selects one below. Default is `0` (main diagonal).
31+
- `axis1` (Optional): The axis to be used as the first axis of the 2D sub-arrays from which the diagonals should be taken. Default is `0`.
32+
- `axis2` (Optional): The axis to be used as the second axis of the 2D sub-arrays from which the diagonals should be taken. Default is `1`.
33+
- `dtype` (Optional): The data type of the returned array. If not specified, it is determined from the input array.
34+
- `out` (Optional): An alternative output array to place the result. It must have the same shape as the expected output.
35+
36+
**Return value:**
37+
38+
Returns the sum of the diagonal elements as a scalar or array, depending on the input array's dimensions and the specified parameters.
39+
40+
## Example
41+
42+
This example demonstrates how to use `.trace()` to calculate the sum of the main diagonal elements of a 2D array:
43+
44+
```py
45+
import numpy as np
46+
47+
# Create a 2D array
48+
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
49+
print("Original array:")
50+
print(array_2d)
51+
52+
# Calculate the trace (sum of main diagonal)
53+
trace_value = array_2d.trace()
54+
print("\nTrace (sum of diagonal elements):", trace_value)
55+
```
56+
57+
The output produced by this code is:
58+
59+
```shell
60+
Original array:
61+
[[1 2 3]
62+
[4 5 6]
63+
[7 8 9]]
64+
65+
Trace (sum of diagonal elements): 15
66+
```
67+
68+
This code creates a 3×3 array and calculates the trace by summing the diagonal elements (1 + 5 + 9 = 15).
69+
70+
## Codebyte Example
71+
72+
```codebyte/python
73+
import numpy as np
74+
75+
# Create a 3x3 matrix
76+
matrix = np.array([[2, 0, 1], [1, 1, 0], [0, 1, 2]])
77+
print("Matrix:")
78+
print(matrix)
79+
80+
# Calculate the trace
81+
trace_result = matrix.trace()
82+
print("\nTrace of the matrix:", trace_result)
83+
84+
# Calculate trace with offset
85+
trace_offset_1 = matrix.trace(offset=1)
86+
trace_offset_minus_1 = matrix.trace(offset=-1)
87+
print("Trace with offset 1 (above diagonal):", trace_offset_1)
88+
print("Trace with offset -1 (below diagonal):", trace_offset_minus_1)
89+
```

0 commit comments

Comments
 (0)