Team LiB   Previous Section   Next Section

3.16 Calculating a Matrix Trace

3.16.1 Problem

You want to calculate the trace of a matrix. The trace of a matrix is the summation of values along the matrix's main diagonal.

3.16.2 Solution

Use the following query to calculate the trace of a matrix. In this case, we calculate the trace of the matrix D.

SELECT SUM(Value) Trace 
FROM Matrices
WHERE Matrix='D' and X=Y

The result:

Trace       
----------- 
9

3.16.3 Discussion

When the X and Y coordinates of an element are the same, the element is on the main diagonal. The WHERE clause in this query restricts the results to only those elements. We need to add those elements together, which we do using the SUM function, and we have the trace of the matrix.

    Team LiB   Previous Section   Next Section