Lior Magen
Lior Magen

Reputation: 1573

For a given sparse matrix, how can I multiply it with a given vector of binary values

I have a sparse matrix and another vector and I want to multiply the matrix and vector so that each column of the vector where it's equal to zero it'll zero the entire column of the sparse matrix.

How can I achieve that?

Upvotes: 1

Views: 924

Answers (3)

hpaulj
hpaulj

Reputation: 231325

If you don't like the speed of matrix multiplication, then you have to consider modification of the matrix attributes directly. But depending on the format that may be slower.

To zero-out columns of a csr, you can find the relevant nonzero elements, and set the data values to zero. Then run the eliminate_zeros method to remove those elements from the sparsity structure.

Setting columns of a csc format may be simpler - find the relevant value in the indptr. At least the elements that you want to remove will be clustered together. I won't go into the details.

Zeroing rows of a lil format should be fairly easy - replace the relevant lists with [].

Anyways with familiarity of the formats it should possible to work out alternatives to matrix multiplication. But without doing so, and doing sometimes, I could say which ones are faster.

Upvotes: 0

user1911226
user1911226

Reputation:

The main problem is the size of your problem and the fact you're using Python which is on the order of 10-100x slower for matrix multiplication than some other languages. Unless you use something like Cython I don't see you getting an improvement.

Upvotes: 1

Shivid
Shivid

Reputation: 1343

You didn't mention anything about how the array and matrix are defined, it can be assumed that those are numpy matrix and array... Do you mean something like the following?

import numpy as np
from scipy.sparse import csr_matrix

A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
v = np.array([1, 0, 1])
print(A.dot(v))

if so take a look at here:

https://docs.scipy.org/doc/scipy/reference/sparse.html

Upvotes: 1

Related Questions