使用两个类的矩阵乘法 [英] Matrix Multiplication using two classes

查看:75
本文介绍了使用两个类的矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在我的计算机科学课上,我们正在学习矩阵乘法,但我有点卡住了.我们要乘以不同维度的矩阵.这是第一堂课,我需要帮助弄清楚如何在 for 循环完成后打印我的结果.

So in my Computer Science class we are going over Matrix Multiplication and I got a little stuck. We are to multiply to matrices that are varying in dimensions. Here is the first class and I need help figuring out how to print my results after the for-loops are complete.

public class Main {
    public static void main(String[] args) {
        int[][] a = {{1, 2, -2, 0}, {-3, 4, 7, 2}, {6, 0, 3, 1}};
        int[][] b = {{-1, 3}, {0, 9}, {1, -11}, {4, -5}};
        int[][] c = MatrixMult.mult(a, b);

        for (int r = 0; r < a.length; r++) {
            for (int c = 0; c < b[0].length; r++) {
                //where the results are printed
            }
        }
    }
}

然后这是另一个具有矩阵乘法功能的类.我不知道在 sum+= 后面放什么来完成循环并返回 ans.

Then this is the other class which has the Matrix Multiplication function in it. I couldn't figure out what to put after the sum+= to finish the loops and return ans.

public class MatrixMult {
    public static int[][] mult(int[][] a, int[][] b) {
        int cRows = a.length;
        int cCols = b[0].length;
        int[][] ans = new int[cRows][cCols];

        for (int r = 0; i < cRows; r++) {
            for (int c = 0; j < cCols; c++) {
                int sum = 0;
                for (int r1 = 0; int r1 < a[0].length; r1++) {
                    sum += // I'm not sure what I put here
                }
            }
        }
        return ans;
    }
}

完成后的输出应该是:

-3 43
18 -60
1 -20

推荐答案

我会给你一个提示.

当矩阵 A * B = C 相乘时,您是在迭代 A 的行(变量 i) 和 B 列(变量 j).C[i][j] 等于:

When multiplying matrices A * B = C, you are iterating rows of A (variable i) and columns of B (variable j). C[i][j] is equal to:

(A[i][0] * B[0][j]) + (A[i][1] * B[1][j]) + (A[i][2] * B[2][j]) + ...

您将括号中的值添加到您的总和中,然后将其分配给 C[i][j].

You add the values in brackets to your sum, and then assign it to C[i][j].

尝试通过检查此模式来弄清楚.

Try to figure it out by examining this pattern.

这篇关于使用两个类的矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆