# Simple Causal Moving Average of length n wit zero padding simpleCMA <- function(x, n) { y <- numeric(length(x)) for (i in 1:length(x)) { sum <- 0 for (j in (0:(n-1))) { if (i - j > 0) { sum <- sum + x[i-j] } } y[i] <- sum/n } return(y) } # Causal Moving Average of length n with zero padding filterCMA <- function(x, n) { res <- numeric(n) for(i in 1:length(x)){ res[i] <- sum(x[(max(i-(n-1),1)):i])/n } res } # Moving Average of length n with zero padding filterMA <- function(x, n) { res <- numeric(n) for(i in 1:length(x)) { res[i] <- sum(x[(max(i-floor(n/2),1)):(min(i+floor(n/2),length(x)))])/n } return(res) } # Moving Average from i-M1 to i+M2 with zero padding filterMA_M1M2 <- function(x, M1, M2) { res <- numeric(n) for(i in 1:length(x)) { res[i] <- sum(x[(max(i-M1,1)):(min(i+M2,length(x)))])/n } return(res) } # Causal Weighted Moving Average for coefficients b with zero padding (conv(x,b)) filterCWMA <- function(x, b) { res <- numeric(length(b)) for(i in 1:length(x)) { if (i < length(b)) { res[i] <- sum(rev(b[1:i])*x[1:i]) } else { res[i] <- sum(rev(b)*x[(i-(length(b)-1)):i]) } } return(res) } # Weighted Moving Average for coefficients b with zero padding filterWMA <- function(x, b) { res <- numeric(length(b)) back <- ceiling((length(b)-1)/2) forw <- floor((length(b)-1)/2) for(i in 1:length(x)) { if (i < back + 1) { res[i] <- sum(rev(b[1:(i+forw)])*x[1:(i+forw)]) } else if (i > length(x) - forw) { res[i] <- sum(rev(b[(i-(length(x)-forw-1)):length(b)])*x[((i-back):(i+forw-(i-(length(x)-forw))))]) } else { res[i] <- sum(rev(b)*x[((i-back):(i+forw))]) } } return(res) }