Search code examples
arraysswiftmathswift3operation

Math operations individual elements in 2D Array - Swift


I’m trying to perform different mathematical operations on individual elements of a 2D array (testArray) combined with 1D array (mod). I’ve got the following for generating individual variables but can’t figure out how to get these values back into a new 2D array. Swift 3.0.2.

let testArray: [[Double]] =
    [[0,100,20.1],
     [1,99,19.2],
     [3,98,18.2],
     [5,97,17.3],
     [7,96,16.4],
     [9,95,15.5]]

let mod: [Double] = [0,5,7,14,20,22]

//Math operations on the two above arrays
for var x in 0..<testArray.count {
    var result1 = Double(testArray[x][0])
    var result2 = Double(testArray[x][1] + mod[x])
    var result3 = Double(testArray[x][2] - mod[x])
    print(result1,result2,result3)
}

//output is as follows:
0.0 100.0 20.1
1.0 104.0 14.2
3.0 105.0 11.2
5.0 111.0 3.3
7.0 116.0 -3.6
9.0 117.0 -6.5

//how do I get the same numbers into a new 2D array as follows:
[[0.0,100.0,20.1],
 [1.0,104.0,14.2],
 [3.0,105.0,11.2],
 [5.0,111.0,3.3],
 [7.0,116.0,-3.6],
 [9.0,117.0,-6.5]]

Solution

  • It could be as simple as this,

    var anotherArray: [[Double]] = []
    for x in 0..<testArray.count {
        let result1 = Double(testArray[x][0])
        let result2 = Double(testArray[x][1] + mod[x])
        let result3 = Double(testArray[x][2] - mod[x])
        anotherArray.append([result1, result2, result3])
    }
    print(anotherArray)