【发布时间】:2015-06-29 12:39:46
【问题描述】:
我对我目前的一门 CS 课程的家庭作业感到非常困惑。
问题是创建一个方法来将两个 3x3 矩阵相乘。除了创建另一种方法来添加两个 3x3 矩阵,然后将两者组合并显示输出。一共有3个矩阵,都是用户输入的。
矩阵 1 : (1, 2, 3, 4, 5, 6, 7, 8, 9)
矩阵 2:(9, 8, 7, 6, 5, 4, 3, 2, 1)
矩阵 3:(0、2、4、1、4.5、2.2、1.1、4.3、5.2)
结果输出:(30, 26, 22, 85, 73.5, 56.2, 139.1, 118.3, 95.2)
在我们给出的输出中,矩阵 1 * 矩阵 2 + 矩阵 3 = 输出。
我的主要问题是在输出中显示正确的数字,看起来很简单,但他的数字完全不符合我的数字。我很困惑你只乘加一次,但如果这是真的,没有两个数字可以等于 139.1。
import java.util.Scanner
public class Assignment8 {
public static void printResult(
double[][] m1, double[][] m2, double[][] m3, double[][] resultMatrix, char op1, char op2) {
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m1[0].length; j++)
System.out.print(" " + m1[i][j]);
if (i == m1.length / 2)
System.out.print( " " + op1 + " " );
else
System.out.print( " " );
for (int j = 0; j < m2[0].length; j++)
System.out.print(" " + m2[i][j]);
if (i == m1.length / 2)
System.out.print( " " + op2 + " " );
else
System.out.print( " " );
for (int j = 0; j < m3[0].length; j++)
System.out.print(" " + m3[i][j]);
if (i == m1.length / 2)
System.out.print( " = " );
else
System.out.print( " " );
for (int j = 0; j < resultMatrix[0].length; j++)
System.out.print(" " + resultMatrix[i][j]);
System.out.println();
}
}
public static double[][] multiplyMatrix(double[][] m3, double[][] m4) {
double[][] result = new double[m3.length][m3[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++)
result[i][j] = m3[i][j] * m4[i][j];
}
return result;
}
public static double[][] addMatrix(double[][] m1, double[][] m2) {
double[][] result = new double[m1.length][m1[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++)
result[i][j] = m1[i][j] + m2[i][j];
}
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[][] m1 = new double[3][3];
double[][] m2 = new double[3][3];
double[][] m3 = new double[3][3];
System.out.print("Enter Matrix 1: ");
for(int row = 0; row <m1.length; row++){
for(int column = 0; column < m1[row].length; column++) {
m1[row][column] = input.nextDouble();
}
}
System.out.print("Enter Matrix 2:");
for(int row = 0; row <m2.length; row++){
for(int column = 0; column < m2[row].length; column++) {
m2[row][column] = input.nextDouble();
}
}
System.out.print("Enter Matrix 3:");
for(int row = 0; row <m3.length; row++){
for(int column = 0; column < m3[row].length; column++) {
m3[row][column] = input.nextDouble();
}
}
double multiply[][] = multiplyMatrix(m1, m2);
double add[][] = addMatrix(multiply, m3);
double resultMatrix[][] = addMatrix(add, multiply);
printResult(m1, m2, m3, resultMatrix, '*', '+');
}
}
【问题讨论】:
-
阅读如何使用简单的迭代方法进行矩阵乘法。提示:您不只是将一个矩阵中的数字与另一个矩阵中的相应数字相乘。 en.wikipedia.org/wiki/Matrix_multiplication_algorithm
-
@Refrain94 - 这些是向量矩阵吗?我记得在 CS 中使用微积分,因此向量化矩阵乘法将与“叉积”相关...tutorial.math.lamar.edu/Classes/CalcII/CrossProduct.aspx