XU Yanzhe XU Yanzhe - 4 months ago 7
Swift Question

How to get a subMatrix from a Matrix with Swift

Like Jama package in Java, there is a method:
getMatrix method

Is there any package who has similar function? I've searched for a while but Surge doesn't seem to help. I'm wondering if I need to write a func do that.

Answer

This may be what you're looking for:

func getSubmatrix(_ matrix: [[Double]], i0: Int, i1: Int, j0: Int, j1: Int) -> [[Double]] {
    var result = [[Double]]()

    for row in Array(matrix[i0...i1]) {
         result.append(Array(row[j0...j1]))
    }

    return result
}

You should be able to use it like this:

print(getSubmatrix([[1.3, 4.3, 5.2], [4.2, 1.6, 4.5], [6.8, 8.9, 10.1]], i0: 0, i1: 1, j0: 0, j1: 1))

This is currently in functional style. If you have/create a Matrix object, you can add this as an instance method to it and use self.

Comments