[Java] Matrix 实现矩阵的运算


1. 矩阵的表达式

  •   A m n \ A_{mn}  Amn : A matrix of order m x n;
  • 其中i和m表示行数,j和n表示列数,   A = A m n = ( a i j ) = ( a i j ) m ∗ n \ A=A_{mn}=(a_{ij})=(a_{ij})_{m*n}  A=Amn=(aij)=(aij)mn
    Matrix Expression

a. n阶矩阵或n阶方阵(N-order Matrix )

行数与列数都等于n的矩阵;

b. 零矩阵(Zero Matrix )

所有元素皆为0;

c. 单位矩阵(Identity Matrix)

从左上角到右下角的对角线(即主对角线)上的元素均为1,其余元素全都为0;
Identity Matrix


2. 矩阵的线性运算(Linear Operations)

a. 加减法运算(Addition & Subtraction)

i. 要求

两个矩阵必须是同型矩阵;
  A i 1 j 1 B i 2 j 2 , i 1 = i 2 = m , j 1 = j 2 = n ; \ A_{i_1j_1} B_{i_2j_2},i_1=i_2=m, j_1=j_2=n;  Ai1j1Bi2j2,i1=i2=m,j1=j2=n;
Addition and Subtraction

b. 数乘运算(Scalar Multiplication)

Scalar Multiplication


3. 矩阵的乘法运算(Multiplication)

a. 要求

左边矩阵的列数必须等于右边矩阵的行数;
  A = ( a i 1 j 1 ) , B = ( b i 2 j 2 ) , j 1 = i 2 = n ; \ A=(a_{i_1j_1}),B=(b_{i_2j_2}),j_1=i_2=n;  A=(ai1j1),B=(bi2j2),j1=i2=n;
Multiplication1
Multiplication2

b. 运算规律

  •   ( A B ) C = A ( B C ) \ (AB)C=A(BC)  (AB)C=A(BC)
  •   ( A + B ) C = A C + B C \ (A+B)C=AC+BC  (A+B)C=AC+BC

4. 矩阵的转置(Transposed Matrix)

Transpose

a. 运算规律

  •   ( A T ) T = A \ (A^T)^T=A  (AT)T=A
  •   ( A + B ) T = A T + B T \ (A+B)^T=A^T+B^T  (A+B)T=AT+BT
  •   ( k A ) T = k A T \ (kA)^T=kA^T  (kA)T=kAT
  •   ( A B ) T = B T A T \ (AB)^T=B^TA^T  (AB)T=BTAT

b. 对称矩阵(Symmetric Matrix)

  A T = A , a i j = a j i \ A^T=A, a_{ij}=a_{ji}  AT=A,aij=aji

c. 反对称矩阵(Skew-Symmetric Matrix)

  A T = − A , a i j = a j i \ A^T=-A, a_{ij}=a_{ji}  AT=A,aij=aji


5. 矩阵的方程组运算

  A X = b \ AX=b  AX=b
在这里插入图片描述

a. 运算步骤

  1. 得到增广矩阵(Augmented Matrix)–   [ A ∣ b ] \ [A|b]  [Ab]
  2. 化简得到右边类似单位矩阵(Identity Matrix);
  3. 最右边的列就是答案;

6. Java 实例

import java.text.DecimalFormat;

/**
 * 实现矩阵的运算
 * 
 * @author Regino
 * class Matrix:
 * - height(): return no. of rows(行数)
 * - width(): return no. of columns(列数)
 * - add(Matrix target), multiply(double target): Linear Operations(线性运算)
 * - multiply(Matrix target): Multiplication(乘法运算)
 * - transpose(Matrix target)(): Transposed(转置)
 * - Solve equatino: solve(Matrix target), GaussElimination(Matrix target), setNum(int num): Equation System(解方程组)
 * - print()
 * test:
 * - output: origin & transpose & add & multiply & solve equation
 */
class Matrix {
    private int row;
    private int column;
    private double value[][];
    private int num;

    Matrix() {
    }

    Matrix(int row, int column, double[][] value) {
        this.row = row;
        this.column = column;
        this.value = value;
    }

    int height() {
        return column;
    }

    int width() {
        return row;
    }

    Matrix add(Matrix target) throws Exception {
        if (this.height() != target.height() || this.width() != target.width()) {
            throw new Exception("The two matrices must be identical in addition and subtraction! " +
                    "(加减法运算时两个矩阵必须是同型矩阵!)");
        } else {
            double result[][] = new double[this.row][this.column];
            for (int i = 0; i < this.row; i++) {
                for (int j = 0; j < this.column; j++) {
                    result[i][j] = this.value[i][j] + target.value[i][j];
                }
            }
            Matrix addition = new Matrix(this.row, this.column, result);
            return addition;
        }
    }

    Matrix multiply(double d) {
        double result[][] = new double[this.row][this.column];
        for (int i = 0; i < this.row; i++) {
            for (int j = 0; j < this.column; j++) {
                result[i][j] = d * this.value[i][j];
            }
        }
        Matrix multiplication2 = new Matrix(this.row, this.column, result);
        return multiplication2;
    }

    Matrix multiply(Matrix target) throws Exception {
        if (this.column != target.row) {
            throw new Exception("The number of columns in the left matrix must equal to the number of rows in the right matrix! " +
                    "(乘法运算时左边矩阵的列数必须等于右边矩阵的行数!)");
        } else {
            double result[][] = new double[this.row][this.column];
            double c = 0;
            for (int i = 0; i < this.row; i++) {
                for (int j = 0; j < target.column; j++) {
                    //求C的元素值
                    for (int k = 0; k < this.column; k++) {
                        c += this.value[i][k] * target.value[k][j];
                    }
                    result[i][j] = c;
                    c = 0;
                }
            }
            Matrix multiplication1 = new Matrix(this.row, target.column, result);
            return multiplication1;
        }
    }

    void setNum(int num) {
        this.num = num;
    }

    Matrix transpose() {
        double result[][] = new double[this.column][this.row];
        for (int i = 0; i < this.row; i++) {
            for (int j = 0; j < this.column; j++) {
                result[j][i] = this.value[i][j];
            }
        }
        Matrix transposed = new Matrix(this.column, this.row, result);
        return transposed;
    }

    String solve(Matrix target) {
        //Augmented Matrix
        double aug[][] = new double[this.row][this.column + 1];
        for (int i = 0; i < this.row; i++) {
            for (int j = 0; j < this.column + 1; j++) {
                if (j == this.column) {
                    aug[i][j] = target.value[i][0];
                } else {
                    aug[i][j] = this.value[i][j];
                }
            }
        }
        Matrix augmented = new Matrix(this.row, this.column + 1, aug);
        Matrix solution = GaussElimination(augmented);
        StringBuilder sb = new StringBuilder();
        sb.append("\r\n");
        switch (solution.num) {
            case 0:
                sb.append("AX = B has no solution(方程无解).");
                break;
            case 1:
                sb.append("AX = B has one unique solution(方程有解),\r\n");
                sb.append("X =");
                sb.append(solution.print());
                break;
            default:
                sb.append("AX = B has infinite many solutions(方程有无穷多个解).");
                break;
        }
        return sb.toString();
    }

    Matrix GaussElimination(Matrix augmented) {
        double[][] sol = new double[augmented.row][1];
        //TODO: 1. calculate arbitrary Equation System; 2. catch exception
        //r2-r3,r3*(1/2),r1-r3
        for (int j = 0; j < augmented.column; j++) {
            augmented.value[1][j] -= augmented.value[2][j];
            augmented.value[2][j] *= 0.5;
            augmented.value[0][j] -= augmented.value[2][j];
        }
        //r2*(1/3),r1-r2
        for (int j = 0; j < augmented.column; j++) {
            augmented.value[1][j] /= 3;
            augmented.value[0][j] -= augmented.value[1][j];
        }
        //r3-r1
        for (int j = 0; j < augmented.column; j++) {
            augmented.value[2][j] -= augmented.value[0][j];
        }
        //switch lines: r3->r1, r2->r3, r1->r2
        for (int j = 0; j < augmented.column; j++) {
            double temp0 = augmented.value[0][j];
            double temp1 = augmented.value[1][j];
            double temp2 = augmented.value[2][j];
            augmented.value[0][j] = temp2;
            augmented.value[1][j] = temp0;
            augmented.value[2][j] = temp1;
        }
        //output X
        for (int i = 0; i < augmented.row; i++) {
            sol[i][0] = augmented.value[i][3];
        }
        Matrix solution = new Matrix(augmented.row, 1, sol);
        //set no. of solutions
        solution.setNum(1);
        return solution;
    }

    String print() {
        DecimalFormat df = new DecimalFormat("0.##");
        StringBuilder sb = new StringBuilder();
        sb.append("\r\n");
        for (int i = 0; i < this.row; i++) {
            for (int j = 0; j < this.column; j++) {
                if (j == this.column - 1) {
                    sb.append(df.format(this.value[i][j]) + "\r\n");
                } else {
                    sb.append(df.format(this.value[i][j]) + " ");
                }
            }
        }
        sb.append("------");
        return sb.toString();
    }
}

public class test {
    public static void main(String[] args) {
        double a[][] = {{1, 2, 1}, {2, 2, 3}, {2, 2, 0}};
        double b[][] = {{2}, {0}, {0}};
        Matrix A = new Matrix(a.length, a[0].length, a);
        Matrix B = new Matrix(b.length, b[0].length, b);
        try {
            System.out.println("Matrix A(矩阵 A):" + A.print());
            System.out.println("Matrix B(矩阵 B):" + B.print());
            System.out.println("A x 5.5 =" + A.multiply(5.5).print());
            System.out.println("A x B =" + A.multiply(B).print());
            System.out.println("Transposed Matrix B(矩阵 B的置换):" + B.transpose().print());
            System.out.println("Solve equation AX = B(解方程 AX = B):" + A.solve(B));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

a. 附录

Java程序中用到的方程组的实际运算;
Java Example


原文链接:https://qwert.blog.csdn.net/article/details/104347898

要使用Java实现矩阵运算,可以使用数组来表示矩阵,并编写相应的函数来实现不同的运算。以下是一个简单的示例代码,展示了如何实现矩阵的加法、减法和乘法运算: ```java public class MatrixOperations { public static void main(String[] args) { double[][] matrixA = { {1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}, {1.0, 1.0, 1.0} }; double[][] matrixB = { {2.0, 2.0, 2.0}, {2.0, 2.0, 2.0}, {2.0, 2.0, 2.0} }; double[][] result = addMatrices(matrixA, matrixB); printMatrix(result); result = subtractMatrices(matrixA, matrixB); printMatrix(result); result = multiplyMatrices(matrixA, matrixB); printMatrix(result); } public static double[][] addMatrices(double[][] matrixA, double[][] matrixB) { int rows = matrixA.length; int cols = matrixA = matrixA[i][j + matrixB[i][j]; } } return result; } public static double[][] subtractMatrices(double[][] matrixA, double[][] matrixB) { int rows = matrixA.length; int cols = matrixA = matrixA[i][j - matrixB[i][j]; } } return result; } public static double[][] multiplyMatrices(double[][] matrixA, double[][] matrixB) { int rowsA = matrixA.length; int colsA = matrixA += matrixA[i][k * matrixB[k][j]; } } } return result; } public static void printMatrix(double[][] matrix) { int rows = matrix.length; int cols = matrix + " "); } System.out.println(); } System.out.println(); } } ``` 上述代码中,`addMatrices`函数实现矩阵的加法运算,`subtractMatrices`函数实现矩阵的减法运算,`multiplyMatrices`函数实现矩阵的乘法运算。`printMatrix`函数用于打印矩阵。 你可以根据需要修改矩阵的大小和内容,并调用相应的函数来执行不同的矩阵运算。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [用Java实现矩阵的基本运算矩阵与数字相加,矩阵矩阵相加,矩阵矩阵相乘,矩阵与数字相乘)附有详细代码...](https://blog.csdn.net/m0_58941767/article/details/121137711)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值