矩阵运算程序怎么写

时间:2025-01-17 16:50:56 游戏攻略

矩阵运算可以通过多种编程语言实现,以下是几种常见编程语言的矩阵运算示例:

Java

```java

import java.util.Scanner;

public class Matrices {

public static void main(String[] args) {

Scanner stdIn = new Scanner(System.in);

System.out.println("Enter number of rows and columns for 1st matrix:");

int rows1 = stdIn.nextInt();

int cols1 = stdIn.nextInt();

int[][] arrA = new int[rows1][cols1];

stdIn.nextLine(); // Consume newline

System.out.println("Enter number of rows and columns for 2nd matrix:");

int rows2 = stdIn.nextInt();

int cols2 = stdIn.nextInt();

int[][] arrB = new int[rows2][cols2];

stdIn.nextLine(); // Consume newline

System.out.println("1st matrix:");

printArray(arrA);

System.out.println("2nd matrix:");

printArray(arrB);

System.out.println("Choose (1)Sum or (2)Product? ");

int choice = stdIn.nextInt();

if (choice == 1) {

int[][] arrC = new int[rows1][cols2];

arrC = matrixSum(arrA, arrB);

System.out.println("Resultant Matrix (Sum):");

printArray(arrC);

} else if (choice == 2) {

int[][] arrC = new int[rows1][cols2];

arrC = matrixProduct(arrA, arrB);

System.out.println("Resultant Matrix (Product):");

printArray(arrC);

}

}

public static int[][] matrixSum(int[][] arrA, int[][] arrB) {

int rows = arrA.length;

int cols = arrA.length;

int[][] arrC = new int[rows][cols];

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

arrC[i][j] = arrA[i][j] + arrB[i][j];

}

}

return arrC;

}

public static int[][] matrixProduct(int[][] arrA, int[][] arrB) {

int rowsA = arrA.length;

int colsA = arrA.length;

int rowsB = arrB.length;

int colsB = arrB.length;

if (colsA != rowsB) {

throw new IllegalArgumentException("Matrix dimensions do not match for multiplication.");

}

int[][] arrC = new int[rowsA][colsB];

for (int i = 0; i < rowsA; i++) {

for (int j = 0; j < colsB; j++) {

for (int k = 0; k < colsA; k++) {

arrC[i][j] += arrA[i][k] * arrB[k][j];

}

}

}

return arrC;

}

public static void printArray(int[][] arr) {

for (int i = 0; i < arr.length; i++) {

for (int j = 0; j < arr[i].length; j++) {

System.out.print(arr[i][j] + " ");

}

System.out.println();

}

}

}

```

Python

```python

import numpy as np

创建两个矩阵

A = np.array([[1, 2], [3, 4]])

B = np.array([[5, 6], [7, 8]])

矩阵相加

C = A + B

print("矩阵相加结果:\n", C)

矩阵相乘

D = np.dot(A, B)

print("矩阵相乘结果:\n", D)

矩阵转置

E = A.T

print("矩阵转置结果:\n", E)

```

C++