fork download
  1. #include <mpi.h>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. #include <vector>
  6. #include <cstdlib>
  7.  
  8. using namespace std;
  9.  
  10. // Function to multiply matrices
  11. void matrixMultiply(const vector<vector<int>>& A, const vector<vector<int>>& B, vector<vector<int>>& C, int startRow, int endRow, int N, int P) {
  12. for (int i = startRow; i < endRow; i++) {
  13. for (int j = 0; j < P; j++) {
  14. C[i][j] = 0;
  15. for (int k = 0; k < N; k++) {
  16. C[i][j] += A[i][k] * B[k][j];
  17. }
  18. }
  19. }
  20. }
  21.  
  22. int main(int argc, char* argv[]) {
  23. MPI_Init(&argc, &argv);
  24.  
  25. int rank, size;
  26. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  27. MPI_Comm_size(MPI_COMM_WORLD, &size);
  28.  
  29. int M = 4, N = 4, P = 4; // Dimensions of matrices
  30.  
  31. vector<vector<int>> A(M, vector<int>(N, 0));
  32. vector<vector<int>> B(N, vector<int>(P, 0));
  33. vector<vector<int>> C(M, vector<int>(P, 0));
  34.  
  35. // Master initializes matrices
  36. if (rank == 0) {
  37. for (int i = 0; i < M; i++) {
  38. for (int j = 0; j < N; j++) {
  39. A[i][j] = rand() % 10; // Random values between 0 and 9
  40. }
  41. }
  42. for (int i = 0; i < N; i++) {
  43. for (int j = 0; j < P; j++) {
  44. B[i][j] = rand() % 10;
  45. }
  46. }
  47.  
  48. cout << "Matrix A:\n";
  49. for (const auto& row : A) {
  50. for (int val : row) cout << val << " ";
  51. cout << "\n";
  52. }
  53.  
  54. cout << "\nMatrix B:\n";
  55. for (const auto& row : B) {
  56. for (int val : row) cout << val << " ";
  57. cout << "\n";
  58. }
  59. cout << "\n";
  60. }
  61.  
  62. // Broadcast matrix B to all processes
  63. for (int i = 0; i < N; i++) {
  64. MPI_Bcast(B[i].data(), P, MPI_INT, 0, MPI_COMM_WORLD);
  65. }
  66.  
  67. int rows_per_proc = M / size;
  68. vector<vector<int>> local_A(rows_per_proc, vector<int>(N));
  69. vector<vector<int>> local_C(rows_per_proc, vector<int>(P, 0));
  70.  
  71. for (int i = 0; i < rows_per_proc; i++) {
  72. MPI_Scatter(A[i].data(), N, MPI_INT, local_A[i].data(), N, MPI_INT, 0, MPI_COMM_WORLD);
  73. }
  74.  
  75. int startRow = rank * rows_per_proc;
  76. int endRow = startRow + rows_per_proc;
  77. matrixMultiply(A, B, C, startRow, endRow, N, P);
  78.  
  79. for (int i = 0; i < rows_per_proc; i++) {
  80. MPI_Gather(local_C[i].data(), P, MPI_INT, C[startRow].data(), P, MPI_INT, 0, MPI_COMM_WORLD);
  81. }
  82.  
  83. if (rank == 0) {
  84. cout << "Result Matrix C:\n";
  85. for (const auto& row : C) {
  86. for (int val : row) cout << val << " ";
  87. cout << "\n";
  88. }
  89. }
  90.  
  91. MPI_Finalize();
  92. return 0;
  93. }
  94.  
Success #stdin #stdout #stderr 0.32s 40732KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "using namespace"
Execution halted