armamax: RcppArmadillo row-wise Matrix Optimizer

Description Usage Arguments Details Value Author(s) Examples

Description

Finds the row-wise maximum of a matrix A, and returns a list with optimal values and their position in each row. The returned value is similar to list(values=apply(A,1,max),indices=apply(A,1,which.max), but much faster than this. A search range delimiter may be specified.

Usage

1
armamax(A,b)

Arguments

A

a numeric matrix

b

an optional vector of integer indices limiting the search range

Details

Takes a matrix A and returns the row-wise maximum and it's position in the row as a list. Optionally one can restrict the region that is searched over for each row by specifying an integer vector b. b must be of length nrow(A), and at each position hold a value in 0,…,ncol(A)-1. This is useful if there is some model restriction that defines values in A[i, ] to the left of, and including b[i] as inadmissible. If optimal values and their position are required, armamax does only one calculation for each row (it finds the maximum and remembers it's position at the same time), where list(values=max(A),indices=which.max(A) needs two. This can be seen as an R version of the MATLAB idiom [index, value] = max(A,[],2). On top of that the RcppArmadillo implementation of the loop over rows of A is much faster than the one implied by apply(). See inst/tests.r for some benchmarks.

Value

a list with entries

values

a vector of length nrow(A) with the row-wise maxima of A

indices

a vector of length nrow(A) with the row-wise maxima of A

Author(s)

<florian.oswald@gmail.com>

Examples

 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
## Not run: 
# find the unrestricted row maximum
x1 <- matrix(rnorm(25),nrow=5,ncol=5)
result <- armamax(x1)
all.equal(apply(x1,1,max),as.numeric(result$values))	# TRUE
all.equal(apply(x1,1,which.max),as.numeric(result$indices))	# TRUE


# find the row maximum restricted to lie to the right of b in each row
A <- matrix(replicate(n=4,sample(1:5,size=5,replace=F)),nrow=4,ncol=5,byrow=T)
b <- sample(0:(ncol(A)-1),size=nrow(A),replace=TRUE)

rfun <- function(A,b){
	R.result <- list()
	R.result$values  <- c()
	R.result$indices <- c()
	for (i in 1:nrow(A)){
		R.result$values[i]  <- max(A[i,(b[i]+1):ncol(A)])
		R.result$indices[i] <- which.max(A[i,(b[i]+1):ncol(A)]) + b[i]
	}
	return(R.result)
}

all.equal(R.result$values,as.numeric(armamax(A,b)$values))
all.equal(R.result$indices,as.numeric(armamax(A,b)$indices))
## End(Not run)

floswald/ArmaUtils documentation built on May 16, 2019, 1:23 p.m.