当前位置: 代码迷 >> java >> 将矩阵中的特定元素相乘
  详细解决方案

将矩阵中的特定元素相乘

热度:42   发布时间:2023-07-31 13:32:28.0

我有两个矩阵

A = {{1,2,3},
     {4,5,6},
     {7,8,9}};

B = {{1,2,3,10},
     {4,5,6,11},
     {7,8,9,12},
     {1,2,3,13}};

我想按以下方式乘以它们。 矩阵A中的元素{5,6},{8,9}乘以{1,2},{4,5}(来自B的元素)。 我知道我可以乘以单个索引,但是如何遍历它们呢?

我不确定如何解决这个问题。 如果有人可以给我一个提示,那将是很大的帮助。

我不是在寻找答案。 关于如何使用循环执行此操作的简单逻辑就足够了。

好像您不来聊天。 对不起,我必须跑。 这是您的问题的可能解决方案:

    int A[][] = new int[][]{{1,2,3},
                            {4,5,6},
                            {7,8,9}};
    int B[][] = new int[][]{{1,2,3,10},
                            {4,5,6,11},
                            {7,8,9,12},
                            {1,2,3,13}};

    System.out.println("====================");
    int number = 1;
    for(int rowIndex = A.length - 2; rowIndex < A.length; rowIndex++) {
        for(int colIndex = A[0].length - 2; colIndex < A[0].length; colIndex++) {
            number *= A[rowIndex][colIndex];
            System.out.print(A[rowIndex][colIndex] + "\t");
        }
        System.out.print("\n");
    }
    System.out.println("====================");     
    for(int rowIndex = 0; rowIndex < 2; rowIndex++) {
        for(int colIndex = 0; colIndex < 2; colIndex++) {
            number *= B[rowIndex][colIndex];
            System.out.print(B[rowIndex][colIndex] + "\t");
        }
        System.out.print("\n");
    }
    System.out.println("====================");
    System.out.print("ANSWER IS: " + number);

输出:

====================
5   6   
8   9   
====================
1   2   
4   5   
====================
ANSWER IS: 86400
  相关解决方案