Reputation: 5420
Hi i want to write some extensions for Array operation like:
MatrixProduct
public static double[][] operator *(double[][] matrixA, double[][] matrixB)
MatrixVectorProduct
public static double[] operator *(double[][] matrix, double[] vector)
and some more
Why do i want this? because as you may know there is at the moment non such operation implemented in c# and it feels more natural if i can say matrixC = matrixA * matrixB;
insteed of matrixC = MatrixProduct(matrixA,matrixB);
so is there a way to do this?
because if i do it like this:
public static class ArrayExtension
{
public static double[] operator *(double[][] matrix, double[] vector)
{
// result of multiplying an n x m matrix by a m x 1 column vector (yielding an n x 1 column vector)
int mRows = matrix.Length; int mCols = matrix[0].Length;
int vRows = vector.Length;
if (mCols != vRows)
throw new InvalidOperationException("Non-conformable matrix and vector in MatrixVectorProduct");
double[] result = new double[mRows]; // an n x m matrix times a m x 1 column vector is a n x 1 column vector
Parallel.For(0, mRows, i =>
{
var row = matrix[i];
for (int j = 0; j < mCols; ++j)
result[i] += row[j] * vector[j];
});
return result;
}
}
An Exception tells me i can't combine a static Class and a userdefined operator so is there a work around ?
Upvotes: 0
Views: 964
Reputation: 437854
You can only overload operator *
if one of its operands is a user-defined type, so unfortunately the answer is no.
From MSDN:
To overload an operator on a custom class requires creating a method on the class with the correct signature. The method must be named "operator X" where X is the name or symbol of the operator being overloaded. Unary operators have one parameter, and binary operators have two parameters. In each case, one parameter must be the same type as the class or struct that declares the operator [...]
So you are forced to either involve a custom Matrix
class in the expression, or use a proper method that takes double[]
arguments.
Upvotes: 3