lab_rat
lab_rat

Reputation: 117

How to write a sparse matrix to file as text using scala/breeze?

I'm new to scala and breeze. Please forgive this question if the answer is obvious. I cannot figure out how to write a sparse matrix to file. Here's an example of what I'm talking about:

import breeze.linalg.CSCMatrix

val B = CSCMatrix.zeros[Int](4,4)
B(0,2) = 1

Now, I want to save B to file as text.

I've thought about mapping the elements of B to a string and then writing to file but that seems wrong. Also, I can convert it to a dense matrix and write it to file but that also seems wrong. Interestingly, even if I do convert it to a dense matrix it will still have to be of type Doubles before csvwrite will work. Arg...please save me from spark/scala hell.

Upvotes: 1

Views: 1311

Answers (1)

Ehsan M. Kermani
Ehsan M. Kermani

Reputation: 952

You can use csvwrite which accepts Matrix[Double].

import java.io.File
import breeze.linalg.{CSCMatrix, csvwrite}


val B = CSCMatrix.zeros[Double](4,4)
B(0, 2) = 1.0
csvwrite(new File("myCSCMatrix.txt"), B, separator=' ')

Upvotes: 2

Related Questions