请你用rust编写一个程序,计算两个矩阵的乘积/
时间: 2024-04-14 09:26:52 浏览: 28
当然可以!下面是一个用 Rust 编写的程序,用于计算两个矩阵的乘积:
```rust
fn matrix_multiplication(matrix1: &[Vec<i32>], matrix2: &[Vec<i32>]) -> Vec<Vec<i32>> {
let rows1 = matrix1.len();
let cols1 = matrix1[0].len();
let cols2 = matrix2[0].len();
let mut result = vec![vec![0; cols2]; rows1];
for i in 0..rows1 {
for j in 0..cols2 {
for k in 0..cols1 {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
result
}
fn main() {
let matrix1 = vec![
vec![1, 2, 3],
vec![4, 5, 6],
];
let matrix2 = vec![
vec![7, 8],
vec![9, 10],
vec![11, 12],
];
let multiplication_result = matrix_multiplication(&matrix1, &matrix2);
for row in multiplication_result {
println!("{:?}", row);
}
}
```
这个程序定义了一个 `matrix_multiplication` 函数,接受两个二维矩阵作为参数,并返回它们的乘积矩阵。在 `main` 函数中,我们定义了两个矩阵 `matrix1` 和 `matrix2`,然后调用 `matrix_multiplication` 函数来计算它们的乘积,并打印结果。
请注意,这个程序假设输入的矩阵维度是合法的,即第一个矩阵的列数等于第二个矩阵的行数。如果输入的矩阵维度不符合要求,程序可能会出错。为了简化代码,这里省略了对输入维度的检查。
希望这个程序对你有所帮助!如果你有任何其他问题,请随时提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)