I need to calculate the matrix trace to degrees 3 and 4, and it should be as fast as it is.
The matrix here is the adjacency matrix of a simple graph, therefore it is square, symmetric, its elements are always 1 or 0, and the diagonal elements are always equal to 0.
Optimization is trivial for a trace matrix up to degree 2:
- We only need diagonal entries (i, i) for tracing, skip all the rest
- Since the matrix is symmetric, these entries are only entries of the square of the i-th row and are summed
- And since the entries are only 1 or 0, a square operation may be skipped.
Another idea that I found on Wikipedia was to summarize all the elements of the Hadamard product, i.e. multiplication by input, but I do not know how to extend this method to degrees 3 and 4.
See http://en.wikipedia.org/wiki/Trace_(linear_algebra)#Properties
I may be just blind, but I cannot come up with a simple solution.
In the end, I need a C ++ implementation, but I think this is not important for the question.
Thanks in advance for your help.
source share