【问题标题】:Matrix substraction differences in Python and JavaPython和Java中的矩阵减法差异
【发布时间】:2019-02-28 20:36:31
【问题描述】:

我在 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 中的这个输出。所以我尝试了以下sn-p的代码:

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 

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

【问题讨论】:

  • 你的方法中没有实现Numpy的broadcasting rules,它描述了当矩阵不同维度时如何进行,通常在做矩阵减法时需要。
  • 那么,我可以使用 Java 中的任何方法或库吗?

标签: java python matrix


【解决方案1】:

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

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;
    }

【讨论】:

    猜你喜欢
    • 2019-09-02
    • 1970-01-01
    • 2018-08-22
    • 2021-11-12
    • 2017-11-12
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2016-05-26
    相关资源
    最近更新 更多