math4610

Homework, Material, and Software Manual for Math 4610


Project maintained by tannerwheeler Hosted on GitHub Pages — Theme by mattgraham

Trace of a Matrix

GO BACK TO SOFTWARE MANUAL

Routine Name: trace

Author: Tanner Wheeler

Language: Python. This code can be run on a python 3 compiler. The file can be imported and then the method will run.

Description/Purpose: This will find the trace of a given square matrix.

Input: This method takes one two dimensional array of dimensions nxn as its only input.

Output: This method will return the trace of the array which is a double value.

Usage/Example: First let’s create a matrix a whose dimensions are 3x3 and set its values. If the array doesn’t have square dimensions then it will return an error message.

n = 3
m = 3

a = [[float(0)] * n for i in range(0,m)]

a[0][0] = float(1)
a[0][1] = float(8)
a[0][2] = float(2)
a[1][0] = float(4)
a[1][1] = float(4)
a[1][2] = float(1)
a[2][0] = float(5)
a[2][1] = float(6)
a[2][2] = float(2)

Now we have

a = [[1.0, 8.0, 2.0],
     [4.0, 4.0, 1.0], 
     [5.0, 6.0, 2.0]]

Let’s print the return value of our method.

print(trace(a))

This will print

7.0

to the console.

Implementation/Code: The following is the code for trace(x)

def trace(x):
    if len(x) != len(x[1]):
        return "Error Invalid sizes!"
    
    tmpVal = 0.0
    for i in range(0, len(x)):
        tmpVal = tmpVal + x[i][i]
    
    return tmpVal

Last Modified: December 2018