简体   繁体   中英

C# operator overloading for matrix

I have written a code for operator overloading for matrix as below. But the result for multiplication with a negative sign doesn't work well.

 public static MyMatrix operator -(MyMatrix A, MyMatrix B)
{
    MyMath math = new MyMath();
    return math.matSubtract(A, B);
}

public static MyMatrix operator -(MyMatrix A, float B)
{
    MyMathmath = new MyMath();
    return math.matSubtract(A, B);
}

public static MyMatrix operator -(MyMatrix A)
{
    MyMathmath = new MyMath();
    return math.matMul(A, -1);
}

public static MyMatrix operator *(MyMatrix , MyMatrix B)
{
    MyMath = new MyMath();
    return math.matMul(A, B);
}

I have checked math.matmul and subtract working fine.

Then, I run tests like this:

var A = new MyMatrix(0,1,2,3,4,5,6,7,8);
print(A);
var B = new MyMatrix(0,1,2,3,4,5,6,7,8);
print(B) ;

A = [0 1 2 
     3 4 5 
     6 7 8]

B = [0 1 2 3 4 5 6 7 8]

print(A*-B)
print(-B*A)
print(A*-B*-B);
print(A*(-B)*(-B));
var C = -B;
print(A*C*C)
ans = [-15 -18 -21 -42 -54 -66 -69 -90 -111] ans = [15 18 21 42 54 66 69 90 111] ans= [-180 -234 -288 -558 -720 -882 -936 -1206 -1476] ans= [-180 -234 -288 -558 -720 -882 -936 -1206 -1476] ans= [180 234 288 558 720 882 936 1206 1476]

Could it be the precedence issue or something else?

Thanks in advance.

没关系,这是别名:我正在更新对象值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM