[R] Speeding indexing and sub-sectioning of 3d array

From: Swidan, Firas <swidanf_at_janelia.hhmi.org>
Date: Thu 10 Aug 2006 - 00:36:49 EST


Hi,

I am having a problem with a very slow indexing and sub-sectioning of a 3d array:

> dim(arr)

[1] 245 175 150

For each point in the array, I am trying to calculate the mean of the values in its surrounding:

mean( arr[ (i - radius):(i + radius),

                                (j - radius):(j + radius),
                                (k - radius):(k + radius)] )

Putting that code in 3 for loops

calculateKMedian <- function( arr, radius){

  for( i in (radius + 1):(dim(arr)[1] - radius - 1) ){     for( j in (radius + 1):(dim(arr)[2] - radius - 1) )       for( k in (radius + 1):(dim(arr)[3] - radius - 1) ){

        mediansArr <- mean( arr[ (i - radius):(i + radius),
                                (j - radius):(j + radius),
                                (k - radius):(k + radius)] )

      }

  }
  return(mediansArr)
}

Results in a very slow run:

> system.time( calculateKMedian( a, 3))
[1] 423.468 0.096 423.631 0.000 0.000

If I replace

        mediansArr <- mean( arr[ (i - radius):(i + radius),
                                (j - radius):(j + radius),
                                (k - radius):(k + radius)] )

With an access to the (I,j,k) cell's value

 mediansArr <- arr[i,j,k]

The running time decreases to

> system.time( calculateKMedian( a, 3))
[1] 14.821 0.005 14.829 0.000 0.000

But 14 seconds are still pretty expensive for just scanning the array.

Is there anything I can do to speed the indexing and the sub-sectioning of the 3d array in this case?

Thanks for the help,
Firas.



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu Aug 10 00:45:12 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 10 Aug 2006 - 08:20:22 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.