Wei Zhang
Wei Zhang

Reputation: 325

Why this code (with OpenMP in MEX-file of Matlab) give different results?

I am using OpenMP in building MEX-file for Matlab. I found my code gives different results when using OpenMP for acceleration. I made a simple example of it as below. It suppose to calculate the mean of every vector. Every element in every vector is 1. So the result is supposed be an array of 1. But the result sometimes has other numbers, like 0.333,0.666, or 0. I thought it must be related to the OpenMP for loop. But I can't figure it out. Any suggestion or idea will be appreciate.

#include "mex.h"
#include <vector>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <omp.h>
using namespace std;

void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
    int xx=8;
    int yy[]={2,3,4,5,6,7,8,9};
    vector<vector<double>> data(xx);
    vector<double>mean0(xx);
    int i,ii;
#pragma omp parallel 
{ 
 #pragma omp for
    for (i = 0; i < xx; i++) {
        data[i].resize(yy[i]);
        for (ii = 0; ii < yy[i]; ii++) {
            data[i][ii]=1;
        }
        mean0[i] =accumulate( data[i].begin(), data[i].end(), 0.0)/data[i].size();  
    }
}

    // output
    plhs[0] = mxCreateDoubleMatrix(mean0.size(), 1, mxREAL);
    copy(mean0.begin(), mean0.end(), mxGetPr(plhs[0]));
    return;
}

Upvotes: 1

Views: 92

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60444

You have declared int i,ii; before the parallel section. This causes these variables to be shared.

You are using C++, declare variables where you first initialize them. In the case of loop variables, this looks like this:

for (int i = 0; i < xx; i++) {
   data[i].resize(yy[i]);
   for (int ii = 0; ii < yy[i]; ii++) {
      data[i][ii]=1;
   }
   mean0[i] = ...
}

This improves readability of the code, and also fixes your problem with OpenMP.


By the way, the loop above can also be written with a single call to std::fill.

Upvotes: 1

Related Questions