File: matmul2.R

package info (click to toggle)
r-cran-foreach 1.3.0-2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 628 kB
  • ctags: 4
  • sloc: sh: 76; makefile: 1
file content (38 lines) | stat: -rw-r--r-- 789 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Less inefficient parallel matrix multiply using custom matrix iterator

library(foreach)

iblkcol <- function(a, chunks) {
  n <- ncol(a)
  i <- 1

  nextEl <- function() {
    if (chunks <= 0 || n <= 0) stop('StopIteration')
    m <- ceiling(n / chunks)
    r <- seq(i, length=m)
    i <<- i + m
    n <<- n - m
    chunks <<- chunks - 1
    a[,r, drop=FALSE]
  }

  obj <- list(nextElem=nextEl)
  class(obj) <- c('abstractiter', 'iter')
  obj
}

# generate the input matrices
x <- matrix(rnorm(100), 10)
y <- matrix(rnorm(100), 10)

# multiply the matrices
nw <- getDoParWorkers()
cat(sprintf('Running with %d worker(s)\n', nw))
mit <- iblkcol(y, nw)
z <- foreach(y=mit, .combine=cbind) %dopar% (x %*% y)

# print the results
print(z)

# check the results
print(all.equal(z, x %*% y))