-
输入两个矩阵(nxk, kxm), 计算其乘积的结果。 模板如下
import java.util.Scanner;
/**
*
* @author Administrator 矩阵乘法
*/
public class MatrixMultiply {
public static void main(String[] args) {
// 0. 定义变量
// 1. 获取输入第一个矩阵1
// 2. 获取输入第二个矩阵
// 3. 相乘
// 4. 打印
}
public double[][] input() {
}
// matrix1: nXk
// matrix2: kXm
// matrixResult: nXm
public double[][] multiply(double[][] matrix1, double[][] matrix2) {
}
// 打印矩阵
public void print(double[][] matrix) {
}
//打印矩阵相乘的等式
/* 1 1 1
1 2 3 4 3 3 3 30 30 30
2 2 2 2 * 5 5 5 = 22 22 22
3 3 3 3 2 2 2 33 33 33
*/
public void print(double[][] matrix1, double[][] matrix2, char op,
double[][] result) {
}
}
/**
* 矩阵1:
1 2 3 4
2 2 2 2
3 3 3 3
*
* 矩阵2:
1 1 1
3 3 3
5 5 5
2 2 2
*
矩阵相乘結果为:
30.0 30.0 30.0
22.0 22.0 22.0
33.0 33.0 33.0文章来源:https://www.toymoban.com/news/detail-758503.html
*/
import java.util.Scanner;
/**
*
* @author Administrator 矩阵乘法
*/
public class MatrixMultiply {
public static void main(String[] args) {
// 0. 定义变量
double[][] matrix1, matrix2, matixResult;
MatrixMultiply matrixMultiply = new MatrixMultiply();
// 1. 获取输入第一个矩阵1
matrix1 = matrixMultiply.input();
System.out.println("输入的矩阵1为:");
matrixMultiply.print(matrix1);
// 2. 获取输入第二个矩阵
matrix2 = matrixMultiply.input();
System.out.println("输入的矩阵2为:");
matrixMultiply.print(matrix2);
// 3. 相乘
matixResult = matrixMultiply.multiply(matrix1, matrix2);
System.out.println("矩阵相乘結果为:");
matrixMultiply.print(matixResult);
// 4. 打印
}
public double[][] input() {
// 0.定义变量
double[][] matrix;
int row, col;
// 1. 输入行数与列数
Scanner scanner = new Scanner(System.in);
System.out.print("请输入矩阵的行与列数(row, col):");
row = scanner.nextInt();
col = scanner.nextInt();
matrix = new double[row][col];
System.out.println("请输入矩阵(" + row + "," + col + ")的元素:");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
matrix[i][j] = scanner.nextDouble();
}
}
return matrix;
}
// matrix1: nXk
// matrix2: kXm
// matrixResult: nXm
public double[][] multiply(double[][] matrix1, double[][] matrix2) {
double[][] matrixResult = new double[matrix1.length][matrix2[0].length];
int n, k, m;
n = matrix1.length;
k = matrix1[0].length;
m = matrix2[0].length;
if (k != matrix2.length) {
System.out.println("两个矩阵不能相乘!");
return null;
}
// 相乘
// 结果第一个元素
// 从01-0m
for (int p = 0; p < n; p++) {
for (int q = 0; q < m; q++) {
double sum = 0;
for (int i = 0; i < k; i++) {
sum += matrix1[p][i] * matrix2[i][q];
}
matrixResult[p][q] = sum;
}
}
return matrixResult;
}
// 打印矩阵
public void print(double[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
}
public void print(double[][] matrix1, double[][] matrix2, char op,
double[][] result) {
}
}
/**
* 矩阵1:
1 2 3 4
2 2 2 2
3 3 3 3
*
* 矩阵2:
1 1 1
3 3 3
5 5 5
2 2 2
*
矩阵相乘結果为:
30.0 30.0 30.0
22.0 22.0 22.0
33.0 33.0 33.0
*/文章来源地址https://www.toymoban.com/news/detail-758503.html
到了这里,关于求矩阵的乘法(Java语言)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!