Juliana
Juliana

Reputation: 103

MATLAB smooth function in R

I am trying to create MATLAB smooth function code in R.

The following is the calculation for the function smooth in MATLAB website:

yy = smooth(y) smooths the response data in column vector y using a moving average filter.

The first few elements of yy follow.

yy(1) = y(1)
yy(2) = (y(1) + y(2) + y(3))/3
yy(3) = (y(1) + y(2) + y(3) + y(4) + y(5))/5
yy(4) = (y(2) + y(3) + y(4) + y(5) + y(6))/5
...

The following is the R code that I have Built:

ma <- function(data){
        output <- vector(mode = "double", length = length(data))
        for(i in 1:length(data)){
                for(j in 1:length(output)){
                        if(j == 1){
                                 output[j] <- data[1]
                        } else if(j == 2) {
                                 output[j] <- (data[1] + data[2] + data[3])/3
                        } else if(j >= 3) {
                                output[j] <- (data[i] + data[i + 1] + data[i + 2] + data[i + 3] + data[i + 4])/5 
                        } 
                
                }
        }
     output   
} 

I am using this vector for test:

n  = 1000
x  = seq(-pi, pi, length.out = n)

teste <- ma(x)

The problem is: it only returns the two first values of the vector. Everything else is NA.

Upvotes: 0

Views: 332

Answers (1)

Onyambu
Onyambu

Reputation: 79288

One way to do this in R is use stats::convolve or use stats::filter both work just fine.

smooth <- function(y ){
  h <- c(head(y, 1), mean(head(y, 3)))
  t <- c(mean(tail(y, 3)), tail(y, 1))
  m <- stats::convolve(y, rep(1/5, 5), type = "filter")
  c(h, m, t)
}

eg:

 R> y <- c(5, 3, 7, 10, 4, 9, 12, 2, 1, 5)
 R> smooth(y)
 [1] 5.000000 5.000000 5.800000 6.600000 8.400000 7.400000 5.600000 5.800000
 [9] 2.666667 5.000000

MATLAB:

 >> y = [5, 3, 7, 10, 4, 9, 12, 2, 1, 5]
 >> smooth(y)

  ans =

      5.0000
      5.0000
      5.8000
      6.6000
      8.4000
      7.4000
      5.6000
      5.8000
      2.6667
      5.0000

Upvotes: 3

Related Questions