Skip to content

Instantly share code, notes, and snippets.

@Jerrynet
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save Jerrynet/5372ccec95e7a3d13e4b to your computer and use it in GitHub Desktop.

Select an option

Save Jerrynet/5372ccec95e7a3d13e4b to your computer and use it in GitHub Desktop.
Multi-Dimensional Matrix
import Cocoa
//No bounds checking
struct Matrix {
let dims:[Int]
let increaseDim:[Int]
var grid: [Double]
init(dim: Int...) {
self.dims = dim
var tmpInDim:[Int] = [1]
var totalElement = 1
for tmpvar in dim {
totalElement *= tmpvar
}
for i in 1..<dim.count {
tmpInDim.append(tmpInDim[i-1]*dim[i-1]);
}
self.increaseDim = tmpInDim
grid = Array(count: totalElement, repeatedValue: 0.0)
}
subscript(index:Int...) -> Double {
get {
var ind = 0
for i in 0..<index.count {
ind += index[i]*self.increaseDim[i]
}
return grid[ind]
}
set(newValue) {
var ind = 0
for i in 0..<index.count {
ind += index[i]*self.increaseDim[i]
}
grid[ind] = newValue
}
}
}
//Example (3D matrix)
var e = Matrix(dim: 2,3,4)
//Use subscript,
e[0,2,2] = 4
//Or index
e[23] = 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment