# Kronecker Power of sparse matrices problem

Why the following code does not work? I try it also in loops.

import numpy

from scipy import sparse

from scipy.sparse import coo_matrix

def SparseMatrixPower(A,p):
if p == 1:
return(A)
elif Mod(p,2):
return(SparseMatrixPower(A,SparseMatrixProduct(A,A)), (p - 1) / 2)
else:
return(SparseMatrixPower(SparseMatrixProduct(A,A), p / 2))

def SparseMatrixProduct(A,B):
return(sparse.kron(A,B)+sparse.kronsum(A,B))

A=sparse.coo_matrix([[0,1,2],[1,1,2],[2,2,3]])
B=sparse.coo_matrix([[0,1,2],[1,1,2],[2,2,3]])
SparseMatrixProduct(A,B)
SparseMatrixPower(A,3)

edit retag close merge delete

Sort by ยป oldest newest most voted

It seems you are confusing calls to SparseMatrixProduct and SparseMatrixPower. Indeed, SparseMatrixPower(A,A) is meaningless (the second argument should be an integer not a matrix).

When p is odd, your code try to make two steps at once (see the (p-1)/2). To understand the algorithm that is behind your code, I would suggest to separate the add/multiply (p -> p-1) part and the double/squaring (p -> p/2) part as follows :

sage: def SparseMatrixPower(A, p):
....:     if p == 1:
....:         return(A)
....:     elif Mod(p, 2):
....:         return SparseMatrixProduct(A, SparseMatrixPower(A, p-1))
....:     else:
....:         return SparseMatrixPower(SparseMatrixProduct(A, A), p/2)


That said, if you plan to play a lot with twose objects, I would suggest to define a class for them and define a __mul__method to define the product. Then Sage has generic double-and-add (or multiply-and-square) to automatically define the power, see for example https://doc.sagemath.org/html/en/refe...

more

Yes, this is typo, I repaired my code. It does not work as well.

( 2020-05-12 13:10:38 +0100 )edit

It is not completely fixed:

SparseMatrixPower(A,SparseMatrixProduct(A,A))


does not makes sense since the second argument of SparseMatrixPower should be a number, not a matrix.

( 2020-05-12 15:31:56 +0100 )edit