This program performs a matrix-vector multiply using MPI to split the computation up. It is not extremely robust (for example, it doesn't handle the case where the number of MPI processes does not divide evenly into the dimensions of the matrix), but I mainly wanted to get some practice using MPI. Is my use of the functions correct, and what are some ways I can improve this code?
#include <iostream>
#include <string>
#include <boost/mpi.hpp>
#include <numeric>
void matVecMult( double ** mat, double * vec, double * result, int beg, int end, unsigned N) {
for (auto i = beg; i < end; i++) {
result[i] = std::inner_product(mat[i], mat[i] + N, vec, 0.0);
}
}
int main(int argc, char ** argv) {
boost::mpi::environment env;
boost::mpi::communicator world;
int dim = (argc > 1) ? std::stoi(argv[1]) : 4;
auto N = static_cast<unsigned>(dim);
auto **matrix = new double *[N]();
auto *vector = new double[N]();
auto *result = new double[N]();
for(unsigned i = 0; i < N; i++){
matrix[i] = new double[N]();
for(unsigned j = 0; j < N; j++){
if(i==j) {matrix[i][j] = i+j;}
}
vector[i] = i + i;
}
int beg = world.rank() * (N/world.size());
int end = beg + (N/world.size());
matVecMult(matrix, vector, result, beg, end, N);
world.isend(0, world.rank(), result + beg, (N/world.size()));
if(world.rank() == 0){
for(int i = 0; i < world.size(); i++) {
world.recv(i,i, result+(i*N/world.size()), (N/world.size()));
}
}
for(unsigned i = 0; i < N; i++){
delete[] matrix[i];
}
delete[] matrix;
delete[] vector;
delete[] result;
return 0;
}