#include <mpi.h>
#include <stdio.h>
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Assumptions based on problem: 7 ranks, each with part of the data
const int rows_per_rank = 25; // Each rank handles 25 rows
const int total_columns = 100; // Total columns in the matrix
float apart[rows_per_rank][total_columns]; // Partial matrix on each rank
float b[total_columns]; // Vector for multiplication
float cpart[rows_per_rank]; // Partial result on each rank
float ctotal[rows_per_rank * size]; // Final result (gathered from all ranks)
// Initialize the matrix 'apart' and vector 'b' with some values
// For example, here we fill them with 1s to simplify.
for (int i = 0; i < rows_per_rank; i++) {
for (int k = 0; k < total_columns; k++) {
apart[i][k] = 1.0f; // Example value, could be anything
}
}
// Initialize vector 'b' with 1s (again, as an example)
for (int k = 0; k < total_columns; k++) {
b[k] = 1.0f;
}
// Each rank calculates its part of the matrix-vector product
for (int i = 0; i < rows_per_rank; i++) {
cpart[i] = 0.0f;
for (int k = 0; k < total_columns; k++) {
cpart[i] += apart[i][k] * b[k];
}
}
// Use MPI_Allgather to gather the partial results from all ranks into 'ctotal'
MPI_Allgather(cpart, rows_per_rank, MPI_FLOAT,
ctotal, rows_per_rank, MPI_FLOAT,
MPI_COMM_WORLD);
// For demonstration, let's print the results on rank 0
if (rank == 0) {
printf("Final result vector (gathered from all ranks):\n"); for (int i = 0; i < rows_per_rank * size; i++) {
}
}
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPG1waS5oPgojaW5jbHVkZSA8c3RkaW8uaD4KCmludCBtYWluKGludCBhcmdjLCBjaGFyKiogYXJndikgewogICAgTVBJX0luaXQoJmFyZ2MsICZhcmd2KTsKCiAgICBpbnQgcmFuaywgc2l6ZTsKICAgIE1QSV9Db21tX3JhbmsoTVBJX0NPTU1fV09STEQsICZyYW5rKTsKICAgIE1QSV9Db21tX3NpemUoTVBJX0NPTU1fV09STEQsICZzaXplKTsKCiAgICAvLyBBc3N1bXB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