Inserting a sparse vector into a sparse matrix

71 Views Asked by At

I want to set the column of a sparse matrix using a sparse matrix and a sparse vector. Tried to check the relevant documents but I got stuck on this part. Is this possible? If it helps I'm building with cabal. I'm ok with changing/adding libraries as long as they can handle sparse matrices and vectors combined.

import Data.Sparse.SpMatrix
import Data.Sparse.SpVector 
import Numeric.LinearAlgebra.Sparse

main :: IO ()
main = do
let m1 = fromListSM (3,3) 
        [(0,0,1)
        ,(1,1,2)
        ,(2,2,3)
        ] :: SpMatrix Double
    let v = fromListSV 3 [(0,1),(1,4),(2,9)] :: SpVector Double
    let m2 = ...

How can I define m2 here for this to work? It should be just like m1, but with the middle column exchanged for v.

In this example the expected outcome for m2 is

1 1 _
_ 4 _ 
_ 9 3
2

There are 2 best solutions below

2
Pompan On BEST ANSWER

I was missing a related module which contained what I wanted.

import Data.Sparse.Common

Now all I needed was to define m2 as this:

let m2 = insertCol m1 v 1
2
amalloy On

I don't see an obviously great way to do this operation using the matrix-based APIs in sparse-linear-algebra. However, the constructors are exported, and you can clearly see an SpMatrix is just an IntMap (IntMap a) with a dimension, and an SpVector is just an IntMap a with a dimension. So if you can't find any cleverer approach, you can just reach inside and insert the row you want into the underlying map.