0

I'm trying to define a type for a matrix (two dimensional array). I have this:

scala> type DMatrix[T] = Array[Array[T]]
defined type alias DMatrix

and then I define de DMatrix:

scala> def DMatrix = Array.ofDim[Double](2,2)
DMatrix: Array[Array[Double]]

So far so good. The problem now is how to work with th DMatrix. I've tried some examples but nothing happens:

scala> DMatrix(0)(0) = 1.0

scala> DMatrix
res40: Array[Array[Double]] = Array(Array(0.0, 0.0), Array(0.0, 0.0))

scala> DMatrix(0)
res41: Array[Double] = Array(0.0, 0.0)

scala> DMatrix(0) = Array(1.0,2.1)

scala> DMatrix(0)
res43: Array[Double] = Array(0.0, 0.0)

so, the question is how to use this DMatrix type?

thanks in advance

2
  • "nothing happens" - what did you expect would happen? Commented Dec 29, 2016 at 13:05
  • I want to fill the DMatrix with values, e.g. in position (0)(0) = 2.3, in position (1)(0) = 3.6 and after that I want to use those values invoking the DMatrix Commented Dec 29, 2016 at 13:09

1 Answer 1

2

There's just a tiny but crucial mistake here - in:

scala> def DMatrix = Array.ofDim[Double](2,2)

You've used def instead of val to declare DMatrix: that means that the expression is evaluated anew everytime you access it, so when you modify the values in the arrays, the result is "thrown away" in favor of a new DMatrix instance.

Changing it to val would fix the issue and you'll see all changes:

scala> val DMatrix = Array.ofDim[Double](2,2)
DMatrix: Array[Array[Double]] = Array(Array(0.0, 0.0), Array(0.0, 0.0))

scala> DMatrix(0)(0) = 1.0

scala> DMatrix
res1: Array[Array[Double]] = Array(Array(1.0, 0.0), Array(0.0, 0.0))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.