Skip to content
Prev 175424 / 398506 Next

Matrix max by row

Rolf Turner wrote:
hmm, since i was called by name (i'm grateful, rolf), i feel obliged to
check the matters myself:

    # dummy data, presumably a 'large matrix'?
    n = 5e3
    m = matrix(rnorm(n^2), n, n)

    # what is to be benchmarked...
    waku = expression(matrix(apply(m, 1, max), nrow(m)))
    bert = expression(do.call(pmax,data.frame(m)))

    # to be benchmarked
    library(rbenchmark)
    benchmark(replications=10, order='elapsed', columns=c('test',
'elapsed'),
       waku=matrix(apply(m, 1, max), nrow(m)),
       bert=do.call(pmax,data.frame(m)))

takes quite a while, but here you go:

    #   test elapsed
    # 1 waku  11.838
    # 2 bert  20.833

where bert's solution seems to require a wonder to 'be considerably
faster for large matrices'.  to have it fair, i also did

    # to be benchmarked
    library(rbenchmark)
    benchmark(replications=10, order='elapsed', columns=c('test',
'elapsed'),
       bert=do.call(pmax,data.frame(m)),
       waku=matrix(apply(m, 1, max), nrow(m)))

    #  test elapsed
    # 2 waku  11.695
    # 1 bert  20.912
   
take home point: a good product sells itself, a bad product may not sell
despite aggressive marketing.

rolf, thanks for pointing this out.

cheers,
vQ