# 非物件導向版本

```class Matrix {
public static void main(String[] args) {
double A[][] = {{1,2}, {3,4}};
double B[][] = {{5,6}, {7,8}};
double C[][] = new double[2][2];
double D[][] = new double[2][2];
System.out.println("========A========");
print(A);
System.out.println("========B========");
print(B);
System.out.println("========C=A+B====");
print(C);
dot(A, B, D);
System.out.println("========D=A*B====");
print(D);
System.out.println("========sum======");
double sum = sum(D);
System.out.println("sum(D)="+sum);
not(D);
System.out.println("========not(D)========");
print(D);

double X[][] = {{1,2,3}, {4, 5, 6}};

System.out.println("==========X===========");
print(X);
double T[][] = transform(X);
System.out.println("==========T===========");
print(T);

}

public static void print(double A[][])
{
for (int i=0; i<A.length; i++)
{
for (int j=0; j<A[0].length; j++)
System.out.print(A[i][j]+" ");
System.out.println();
}
}

public static void not(double A[][])
{
for (int i=0; i<A.length; i++)
for (int j=0; j<A[0].length; j++)
A[i][j] = -A[i][j];
}

public static double sum(double A[][])
{
double total = 0;
for (int i=0; i<A.length; i++)
for (int j=0; j<A[0].length; j++)
total += A[i][j];
}

public static void add(double A[][], double B[][], double C[][])
{
for (int i=0; i<A.length; i++)
for (int j=0; j<A[0].length; j++)
C[i][j] = A[i][j] + B[i][j];
}

public static void dot(double A[][], double B[][], double C[][])
{
for (int i=0; i<C.length; i++)
for (int j=0; j<C[0].length; j++)
{
double sum = 0;
for (int k=0; k<2; k++)
sum = sum+A[i][k]*B[k][j];
C[i][j] = sum;
}
}

public static double[][] transform(double A[][])
{
double T[][] = new double[A[0].length][A.length];
for (int i=0; i<T.length; i++)
for (int j=0; j<T[0].length; j++)
T[i][j] = A[j][i];
return T;
}
}
```

# 物件導向版本

```class Matrix {
public double m[][];

public Matrix(double a[][]) {
m = new double[a.length][a[0].length];
for (int i=0; i<a.length; i++) {
for (int j=0; j<a[0].length; j++) {
m[i][j] = a[i][j];
}
}
}

public void print()
{
for (int i=0; i<m.length; i++)
{
for (int j=0; j<m[0].length; j++)
System.out.print(m[i][j]+" ");
System.out.println();
}
}

public static void main(String[] args) {
Matrix A = new Matrix(new double[][]{{1,2}, {3,4}});
System.out.println("========A========");
A.print();
}
}
```