1

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 ?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

It seems that there is a problem with the min function. Error message :" Expression was too complex to be solve in reasonable time; consider breaking up the expression into distinct sub expressions" I tried to replace the min by (i<=j ? i :j) but the message remains the same
Are you sure you typed it right? I tested on a playground before posting.
Are your a and b vars Doubles?
to be true the exact code I used is the following let C = (1...n).map {i in (1...n).map {j in exp(Double(i + j) * m + 0.5 * sigma2 * (Double(i + j) + 2 * Double(min(i,j))) ) } }
m and sigma2 are let doubles
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.