[R] Looping over a matrix passed to .C
Nathan S. Watson-Haigh
nathan.watson-haigh at csiro.au
Wed Feb 11 03:49:49 CET 2009
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
I've written a function in R which takes a symmetrical matrix as input and
processes all triplicate combinations of values from the matrix. The function
looks something like:
my_fun <- function(m) {
if( nrow(mat) != ncol(mat) ) {
stop("'m' must be a square matrix")
}
size <- nrow(m)
for(x in 1:(size -2)) {
for(y in (x+1):(size -1)) {
xy <- m[x,y]
for(z in (y+1):size ) {
xz <- m[x,z]
yz <- m[y,z]
# do something with xy, xz, yz
}
}
}
}
I'd like to speed this up since when size gets > a few thousand, I estimate it
would take 3yrs to complete the "do something" task. I could implement the "do
something" in C and have it called from within the nested for loops in R, but I
think I should get better performance if I implement the for loops in C as well.
As such, I'm trying to get my head around looping through matrix values when
passed to .C()
As I understand it, once a matrix (n x m in size) is passed to .C() it is seen
as an unwrapped array of length n*m. Could someone help/guide me in implementing
this?
Cheers,
Nathan
- --
- --------------------------------------------------------
Dr. Nathan S. Watson-Haigh
OCE Post Doctoral Fellow
CSIRO Livestock Industries
Queensland Bioscience Precinct
St Lucia, QLD 4067
Australia
Tel: +61 (0)7 3214 2922
Fax: +61 (0)7 3214 2900
Web: http://www.csiro.au/people/Nathan.Watson-Haigh.html
- --------------------------------------------------------
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iEYEARECAAYFAkmSPM0ACgkQ9gTv6QYzVL5HbwCfRdA+7madbF5zuoKJRbuh4/tE
sLwAn39h1JxNF6MjaF+AgxCq3XVe0X7T
=KEDP
-----END PGP SIGNATURE-----
More information about the R-help
mailing list