Displaying 1 result from an estimated 1 matches for "diffmatrix".
2011 Apr 27
1
matrix of higher order differences
Is there an easy way to turn a vector of length n into an n by n matrix, in
which the diagonal equals the vector, the first off diagonal equals the
first order differences, the second... etc. I.e. to do this more
efficiently:
diffmatrix <- function(x){
n <- length(x);
M <- diag(x);
for(i in 1:(n-1)){
differences <- diff(x, dif=i);
for(j in 1:length(differences)){
M[j,i+j] <- differences[j]
}
}
M[lower.tri(M)] <- t(M)[lower.tri(M)];
return(M);
}
x <- c(1,2,3,5,7,11,13,17,19);
diffmatrix(x);
-...