Created
May 7, 2024 01:10
-
-
Save robertmryan/0fe382a557df810bbbe3a6f0a0a218c9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var valuesA: [Float] = [2, 0.5, 9, 1, 18] | |
let rowsA = Int32(valuesA.count) | |
let columnsA = Int32(valuesA.count) | |
var rowIndicesA = Array(0 ..< rowsA) | |
var columnStarts = Array(0 ... valuesA.count) | |
var valuesB: [Float] = [3, 5, 8, 7, 2, | |
1, 4, 9, 1, 3, | |
2, 7, 3, 1, 2, | |
5, 4, 9, 1, 6, | |
4, 2, 9, 6, 7] | |
let count = valuesB.count | |
valuesA.withUnsafeMutableBufferPointer { aPointer in | |
valuesB.withUnsafeMutableBufferPointer { bPointer in | |
rowIndicesA.withUnsafeMutableBufferPointer { rowsPointer in | |
columnStarts.withUnsafeMutableBufferPointer { columnsPointer in | |
var a = SparseMatrix_Float( | |
structure: SparseMatrixStructure( | |
rowCount: rowsA, | |
columnCount: columnsA, | |
columnStarts: columnsPointer.baseAddress!, | |
rowIndices: rowsPointer.baseAddress!, | |
attributes: SparseAttributes_t(), | |
blockSize: 1 | |
), | |
data: aPointer.baseAddress! | |
) | |
let results = Array<Float>(unsafeUninitializedCapacity: count) { | |
resultsPointer, | |
initializedCount in | |
let b = DenseMatrix_Float( | |
rowCount: rowsA, | |
columnCount: columnsA, | |
columnStride: rowsA, | |
attributes: SparseAttributes_t( | |
transpose: true, | |
triangle: SparseLowerTriangle, | |
kind: SparseSymmetric, | |
_reserved: 0, | |
_allocatedBySparse: false | |
), | |
data: bPointer.baseAddress! | |
) | |
let c = DenseMatrix_Float( | |
rowCount: rowsA, | |
columnCount: columnsA, | |
columnStride: rowsA, | |
attributes: SparseAttributes_t( | |
transpose: true, | |
triangle: SparseLowerTriangle, | |
kind: SparseSymmetric, | |
_reserved: 0, | |
_allocatedBySparse: false | |
), | |
data: resultsPointer.baseAddress! | |
) | |
SparseMultiply(a, b, c) | |
initializedCount = count | |
} | |
// Print the result matrix | |
let formatter = NumberFormatter() | |
formatter.minimumFractionDigits = 1 | |
formatter.formatWidth = 5 | |
for row in 0..<rowsA { | |
for column in 0..<columnsA { | |
let value = results[Int(row * columnsA + column)] | |
print(formatter.string(for: value)!, terminator: " ") | |
} | |
print() | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment