Writing an MxN matrix ( M rows, N columns ) to a CSV file:
My first attempt, using map, works, but creates N references to the stringbuffer. It also writes an unnecessary comma at the end of each row.
def matrix2csv(matrix:List[List[Double]], filename: String ) = {
val pw = new PrintWriter( filename )
val COMMA = ","
matrix.map( row => {
val sbuf = new StringBuffer
row.map( elt => sbuf.append( elt ).append( COMMA ))
pw.println(sbuf)
})
pw.flush
pw.close
}
My second attempt, using reduce, also works but looks clunky:
def matrix2csv(matrix:List[List[Double]], filename: String ) = {
val pw = new PrintWriter( filename )
val COMMA = ","
matrix.map( row => {
val sbuf = new StringBuffer
val last = row.reduce( (a,b)=> {
sbuf.append(a).append(COMMA)
b
})
sbuf.append(last)
pw.println(sbuf)
})
pw.flush
pw.close
}
Any suggestions on a more concise and idiomatic approach ? Thanks.
You can obtain the string representation easily:
val csvString = matrix.map{ _.mkString(", ") }.mkString("\n")
Then you just need to dump it in a file.
Pay attention to end-lines (here "\n" ), they vary according to the platform.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With