Is there an expression (perhaps using np.tensordot
) that most expressively captures a sparse matrix vector multplicatiuon between a block matrix of diagonal blocks and a vector of the corresponding size?
I have a working implementation that performs the exact operations I want, but I used two python loops (see below) instead of an appropriate numpy
command, which probably exists.
For example:
import numpy as np
outer_size = 2
inner_size = 5
shape = (outer_size, outer_size, inner_size)
diag_block = np.arange(np.prod(shape)).reshape(shape)
true_diag = np.bmat([[np.diag(diag_block[i,j]) for j in range(shape[1])] for i in range(shape[0])]).A
x = np.arange(shape[1] * shape[2])
def sparse_prod(diags, x):
outer_size = diags.shape[0]
return np.hstack(sum(diags[i] * x.reshape(outer_size, -1)) for i in range(outer_size))
print(true_diag.dot(x))
print(sparse_prod(diag_block, x))