I need to fill an Array that describes a Matrix [[Double]]. Each element of the matrix is of the following form :
a(i,j) = exp(a*(i+j) + b*min(i,j))
Is there an elegant way of doing that rather than using 2 embedded loops ?
You can use map twice to create your matrix. This is a functional approach that is really just two loops under the hood:
let maxi = 5 // largest acceptable index
let maxj = 3 // largest acceptable index
let a = 2.3
let b = 3.4
let matrix = (0...maxi).map { i in (0...maxj).map { j in exp(a * Double(i + j) + b * Double(min(i, j))) } }
which might be a little easier to read if we format it like this:
let matrix = (0...maxi).map { i in
(0...maxj).map { j in
exp(a * Double(i + j) + b * Double(min(i, j)))
}
}
One advantage this has over using loops is that you can create a matrix that is read-only (let). Of course, you can always make it var if you want it to be mutable.