gpt4 book ai didi

java - Python 和 Java 中的矩阵减法差异

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:22 26 4
gpt4 key购买 nike

我在 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 中实现广播规则?

最佳答案

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

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

关于java - Python 和 Java 中的矩阵减法差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54933858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com