the sparseMatrix function with comments: extension Array where Element == [Double] { // A sparse matrix is a mattrix where all zero's are ommitted. // Normal matrix: Sparse matrix: // 0 1 0 1 // 1 3 0 1 3 // 4 0 2 4 2 // Find the sparse matrix of this matrix. Returns an array of doubles containing the values of the sparse matrix (omitting all zero's) and a SparseMatrixStructure containing information about where the columns start and where the rows start. The values array of the sparse matrix above would be [1, 4, 1, 3, 2]. func sparseMatrix() -> (structure: SparseMatrixStructure, values: [Double]) { let columns = self.transpose() // Get the row indices of the matrix. The row indices of the sparse matrix above would be // [1, 2 column 0 // 0, 1, column 1 // 2] column 2 var rowIndices: [Int32] = columns.map { column in column.indices.compactMap { indexInColumn in if column[indexInColumn] != 0 { return Int32(indexInColumn) } return nil } }.reduce
Topic:
Programming Languages
SubTopic:
Swift
Tags: