6

I'm trying to read a csv file and return it as an array of arrays of doubles (Array[Array[Double]]). It's pretty clear how to read in a file line by line and immediately print it out, but not how to store it in a two-dimensional array.

def readCSV() : Array[Array[Double]] = {
    val bufferedSource = io.Source.fromFile("/testData.csv")
    var matrix :Array[Array[Double]] = null
    for (line <- bufferedSource.getLines) {
        val cols = line.split(",").map(_.trim)
        matrix = matrix :+ cols
    }
    bufferedSource.close
    return matrix
}

Had some type issues and then realized I'm not doing what I thought I was doing. Any help pointing me on the right track would be very appreciated.

elm
  • 20,117
  • 14
  • 67
  • 113
user3413468
  • 247
  • 1
  • 3
  • 9

2 Answers2

6

It seems your question was already answered. So just as a side note, you could write your code in a more scalaish way like this:

def readCSV() : Array[Array[Double]] = {
  io.Source.fromFile("/testData.csv")
    .getLines()
    .map(_.split(",").map(_.trim.toDouble))
    .toArray
}
Helder Pereira
  • 5,522
  • 2
  • 35
  • 52
1

1) You should start with an empty Array unstead of null. 2) You append items to an Array with the operator :+ 3) As your result type is Array[Array[Double]] you need to convert the strings of the csv to Double.

def readCSV() : Array[Array[Double]] = {
    val bufferedSource = io.Source.fromFile("/testData.csv")
    var matrix :Array[Array[Double]] = Array.empty
    for (line <- bufferedSource.getLines) {
        val cols = line.split(",").map(_.trim.toDouble)
        matrix = matrix :+ cols
    }
    bufferedSource.close
    return matrix
}
Sascha Kolberg
  • 7,092
  • 1
  • 31
  • 37
  • Thank you! Turns out this gets you the array of rows, not the array of columns, but it doesn't take much to turn that into the columns. – user3413468 Aug 17 '15 at 17:16