嗨,我想为数组操作编写一些扩展,例如:
矩阵产品
public static double[][] operator *(double[][] matrixA, double[][] matrixB)
矩阵向量积
public static double[] operator *(double[][] matrix, double[] vector)
还有一些
我为什么要这个?因为您可能知道目前在 c# 中实现了非此类操作,如果我可以说它感觉更自然matrixC = matrixA * matrixB;
,matrixC = MatrixProduct(matrixA,matrixB);
那么有没有办法做到这一点?
因为如果我这样做:
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;
}
}
一个异常告诉我我不能将静态类和用户定义的运算符结合起来,所以有解决方法吗?