矩阵乘法的朴素算法(Java语言描述)

算法介绍

这只是一种暴力算法!这只是一种暴力算法!这只是一种暴力算法!
在这里插入图片描述

不会的就去复习复习高等代数/线性代数吧orz

编程实现

public class MatrixMultiplication {

    /**
     * Standard matrix multiplication.
     * Arrays start at 0.
     * Assumes a and b are square.
     */
    private static int [][] multiply(int [][] matrix1, int [][] matrix2) {
        int length = matrix1.length;
        int [][] result = new int[length][length];
        for(int i = 0; i < length; i++) {
            for(int j = 0; j < length; j++) {
                for(int k = 0; k < length; k++) {
                    result[i][j] += matrix1[i][k] * matrix2[k][j];
                }
            }
        }
        return result;
    }

}

测试

public class MatrixMultiplicationTest {
    public static void main(String [] args) {
        int [][] matrix = { { 1, 2 }, { 3, 4 } };
        int [][] c = multiply(matrix, matrix);
        System.out.println( c[0][0] + "\t" + c[0][1] + "\n" + c[1][0] + "\t" + c[1][1]);
    }
}

测试结果:

7	10
15	22
发布了577 篇原创文章 · 获赞 1186 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/weixin_43896318/article/details/104502373
今日推荐