Skip to content
Prev 258127 / 398502 Next

matrix of higher order differences

Jeroen Ooms <jeroenooms <at> gmail.com> writes:
I do not know whether you will call the appended version more elegant,
but at least it is much faster -- up to ten times for length(x) = 1000,
i.e. less than 2 secs for generating and filling a 1000-by-1000 matrix.
I also considered col(), row() indexing:

    M[col(M) == row(M) + k] <- x

Surprisingly (for me), this makes it even slower than your version with
a double 'for' loop.

-- Hans Werner

# ----
diffmatrix <- function(x){
	n <- length(x)
	if (n == 1) return(x)

	M <- diag(x)
	for(i in 1:(n-1)){
		x <- diff(x)           # use 'diff' in a loop
		for(j in 1:(n-i)){     # length is known
			M[j, i+j] <- x[j]  # and reuse x
		}
	}
	M[lower.tri(M)] <- t(M)[lower.tri(M)]
	return(M)
}
# ----