写一个MPI矩阵向量乘法的代码
时间: 2023-06-20 12:03:40 浏览: 98
以下是使用MPI实现矩阵向量乘法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#define ROWS 4
#define COLS 4
int main(int argc, char *argv[]) {
int rank, size;
int i, j;
int matrix[ROWS][COLS] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
int vector[COLS] = {1, 2, 3, 4};
int result[ROWS] = {0};
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (size != COLS) {
printf("Number of processes must match number of columns in matrix.\n");
MPI_Finalize();
return 1;
}
int *submatrix = (int *) malloc(ROWS * sizeof(int));
MPI_Scatter(matrix, ROWS, MPI_INT, submatrix, ROWS, MPI_INT, 0, MPI_COMM_WORLD);
int subresult = 0;
for (i = 0; i < ROWS; i++) {
subresult += submatrix[i] * vector[rank];
}
MPI_Reduce(&subresult, &result[0], 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
printf("Result: ");
for (i = 0; i < ROWS; i++) {
printf("%d ", result[i]);
}
printf("\n");
}
MPI_Finalize();
return 0;
}
```
这个程序将矩阵和向量硬编码为整数数组,然后将矩阵的每一行分发给MPI进程。每个进程计算其分配的行和向量的乘积,并将结果通过MPI_Reduce函数发送到进程0,然后进程0打印结果。
阅读全文