TensorTonicTensorTonic
Problems
Study PlansProjectsNewInterviewPricingFeedback
Problems
Loading...
1 / 1

Matrix Trace

Linear Algebra
Easy

Compute the trace of a square matrix, which is the sum of its main-diagonal entries:

tr⁡(A)=∑i=1NAii\operatorname{tr}(A)=\sum_{i=1}^{N}A_{ii}tr(A)=i=1∑N​Aii​

Here, AAA is an N×NN\times NN×N matrix and AiiA_{ii}Aii​ is its entry in row iii and column iii. Compute the sum directly from indexed elements and return it as a Python float.

Loading visualization...

Examples

Input: A = [[1, 2], [3, 4]]

Output: 5

Explanation: The main diagonal contains 1 and 4.

Input: A = [[2, -1, 0], [3, 5, 1], [0, 2, -2]]

Output: 5

Input: A = [[42]]

Output: 42

Hint 1

Accumulate A[i, i] for i from zero through A.shape[0] - 1.

Hint 2

Convert the final NumPy scalar with float(total).

Requirements

  • Sum the entries whose row and column indices are equal
  • Do not use np.trace or np.diagonal
  • Return a Python float

Constraints

  • A is a nonempty square numeric matrix
  • Matrix entries may be integers or floating-point values
  • Use NumPy only
Try Similar Problems
Matrix TransposeMatrix InverseEigenvaluesMake DiagonalMatrix Normalization

Sign in to take notes on this problem

Case 1
Case 2
Case 3

Accepts: array

You must run your code first.
PrevNext

Matrix Trace

Linear Algebra
Easy

Compute the trace of a square matrix, which is the sum of its main-diagonal entries:

tr⁡(A)=∑i=1NAii\operatorname{tr}(A)=\sum_{i=1}^{N}A_{ii}tr(A)=i=1∑N​Aii​

Here, AAA is an N×NN\times NN×N matrix and AiiA_{ii}Aii​ is its entry in row iii and column iii. Compute the sum directly from indexed elements and return it as a Python float.

Loading visualization...

Examples

Input: A = [[1, 2], [3, 4]]

Output: 5

Explanation: The main diagonal contains 1 and 4.

Input: A = [[2, -1, 0], [3, 5, 1], [0, 2, -2]]

Output: 5

Input: A = [[42]]

Output: 42

Hint 1

Accumulate A[i, i] for i from zero through A.shape[0] - 1.

Hint 2

Convert the final NumPy scalar with float(total).

Requirements

  • Sum the entries whose row and column indices are equal
  • Do not use np.trace or np.diagonal
  • Return a Python float

Constraints

  • A is a nonempty square numeric matrix
  • Matrix entries may be integers or floating-point values
  • Use NumPy only
Try Similar Problems
Matrix TransposeMatrix InverseEigenvaluesMake DiagonalMatrix Normalization

Sign in to take notes on this problem

Case 1
Case 2
Case 3

Accepts: array

You must run your code first.