lundi 27 juin 2016

efficient method of getting neighbour elements for each entry in a matrix


First off, I am using R with the RCpp package while allows me to run C++ code. R is just too slow for my purpose.

I have a matrix (500x500) of integers For each entry, I need to look at its surrounding neighbours (so 8 elements) and determine what the integers are.

I am pretty sure my current method is not efficient at all. I am using 4 for loops to calculate this. My code is below: The outer two loops (i and j) loop through each element of the matrix.

The inner two loops (k and l) loop through the neighbours of the selected matrix. Then I check if any of the neighbours have a 4. If so, I increment a counter. The output matrix will have, as its i and j entry a function of this.

I am looking for a way to make this code efficient and possibly vectorize it. Also note, parallel processing is easily doable. My cluster has 64 cores.

fx2<- cppFunction('NumericMatrix rowSumsC(NumericMatrix x) {
            int nrow = x.nrow(), ncol = x.ncol();
            NumericMatrix outProb(nrow, ncol);
            int kc = 0; int kpre = 0; int ks = 0;
            for (int i = 1; i < (nrow-1); i++) {
              for (int j = 1; j < (ncol-1); j++) {

                //get the submatrix
                //NumericMatrix x( Range(0, 2), Range(0, 2))
                //NumericMatrix subMat =  x( Range(i-1, i+1), Range(j-1, j+1) );
                int sum = 0;
                for(int k = -1; k <= 1; k++){
                  for(int l = -1; l <= 1; k++){
                    if(x(i + k, j + l) == 4){
                      kc++;
                    }
                  }
                } //end of loop
                outProb(i, j) = functionof(kc, ks, kpre);                
              }              
            }
            return outProb;
            }')

Here is now


Aucun commentaire:

Enregistrer un commentaire