Skip to content

Instantly share code, notes, and snippets.

@dlwh
Created June 11, 2013 14:25
Show Gist options
  • Save dlwh/5757259 to your computer and use it in GitHub Desktop.
Save dlwh/5757259 to your computer and use it in GitHub Desktop.
class DiagMatrix[Vec, S](val diagonalVector: Vec)(implicit evidence: Vec <:< Vector[S]) extends Matrix [S]

(The evidence implicit is because you can't write class DiagMatrix[Vec <: Vector[S], S] and expect it to work. Why? because it's apparently too hard to implement.) You would probably want type aliases like

type DenseDiagMatrix[S] = DiagMatrix[DenseVector[S], S]

as well. Or not.

Operators should be defined in terms of operations on the vector. E.g.

object DiagMatrix {
  implicit def multiplyByVector[Vec, S, RHS, ResultType](implicit multiplyElementWise: BinaryOp[Vec, RHS, OpMulScalar, ResultType]): BinaryOp[DiagMatrix[Vec, S], RHS, OpMulMatrix, ResultType] = new BinaryOp[DiagMatrix[Vec, S], RHS, OpMulMatrix, ResultType] {
    def apply(lhs: DiagMatrix[Vec,S], rhs: RHS) = {
       multiplyElementWise(lhs, rhs)
    }
  }

}

(code not compiled or tested.)

That would probably match actual scalar multiplication as well as elementwise multiplication. Probably we only want the latter. Excluding the former would probably involve constraining RHS to be Vec, or something. (DiagMatrix \ Vector can be implemented the same way using either a Field on S, or by asking for OpDiv and just being ok with the fact that you could end up with a weird type if RHS :/ Vec and Vec :* RHS don't have the same result type.)

Making the operations efficient: to the extent that they are defined like the above, they will be basically as efficient as the underlying vector's implementation. Some operations probably can't be defined this way, like DiagMatrix * Matrix... For those, I guess implement the straightforward thing, and we'll improve from there if it turns out to be a problem.

-- David

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment