Python和J中的矩阵减法差异

2024-09-29 00:19:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python和Java中的矩阵减法有一个问题。我在两种编程语言中都遵循相同的步骤,但输出是不同的。你知道吗

import numpy as np
array1 = [[1,3], [5,6],[7,8]]
array1 = np.transpose(array1)

array2 = [[1,0,1]]
array3 = np.subtract(array2,array1)
print(array3)

哪个输出矩阵是这样的:

[[ 0 -5 -6]
[-2 -6 -7]]

这工作很好,在我需要的方式。但是我需要Java的输出。因此,我尝试了以下代码片段:

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

double [][] array2 = new double[][]{
        {1,0,1}
    };

array1 = np.T(array1);
double [][] vysl = np.subtract(array2, array1);

在哪里

public static double[][] subtract(double[][] a, double[][] b) {
    int m = a.length;
    int n = a[0].length;
    double[][] c = new double[m][n];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            c[i][j] = a[i][j] - b[i][j];
        }
    }
    return c;
}

 public static double[][] T(double[][] a) {
    int m = a.length;
    int n = a[0].length;
    double[][] b = new double[n][m];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            b[j][i] = a[i][j];
        }
    }
    return b;
}

但结果不同:

for (int i = 0; i < vysl.length; i++)
    {
        for (int y = 0; y < vysl[0].length; y++)
            System.out.print(vysl[i][y] + " ");
        System.out.println("");
    }

0.0 -3.0 -4.0 

我已经用这个2D循环显示了矩阵。这个矩阵只有1行3列,但是前面的pythom矩阵有2行3列。你能告诉我我做错了什么吗?我可以用Java得到2行3列的矩阵吗?如何在Java中实现广播规则?你知道吗


Tags: newfornp矩阵javapubliclengthint
1条回答
网友
1楼 · 发布于 2024-09-29 00:19:50

我可以看到您的代码中的问题…对于您的用例,下面的代码给出了预期的输出

public static void main(String[] args) {
        double[][] array1 = new double[][] { { 1, 3 }, { 5, 6 }, { 7, 8 } };

        double[][] array2 = new double[][] { { 1, 0, 1 } };

        array1 = np(array1);
        double[][] vysl = subtract(array2, array1);
        System.out.println("complete");
    }


    public static double[][] np(double[][] a) {
        int x = a.length;
        int y = a[0].length;

       double[][] c = new double[y][x];


        for (int i = 0; i < y; i++) {
            for (int j = 0; j < x; j++) {
               c[i][j] = a[j][i];

            }
        }

        return c;
    }

    public static double[][] subtract(double[][] a, double[][] b) {
        int m = b.length;
        int n = b[0].length;
        double[][] c = new double[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                c[i][j] = a[0][j] - b[i][j];
            }
        }
        return c;
    }

相关问题 更多 >