Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix to CSV in Scala

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.

like image 477
k r Avatar asked Nov 08 '11 16:11

k r


1 Answers

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.

like image 144
paradigmatic Avatar answered Sep 23 '22 13:09

paradigmatic