celestialgod

piecewise linear approximation

Mar 22nd, 2016
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.48 KB | None | 0 0
  1. q<-c(18, 15, 24, 23, 18, 22, 19, 29, 22, 25, 20, 19, 18, 20, 26, 32,
  2.      26, 26, 34, 29, 23, 34, 22, 19, 21, 19, 34, 23, 23, 23, 30, 21,
  3.      15, 29, 32, 19, 21, 28, 22, 32, 29, 25, 28, 28, 23, 12, 26, 24,
  4.      27, 14, 38, 27, 28, 25, 38, 34, 25, 37, 15, 28, 15, 23, 23, 28,
  5.      15, 15, 19, 25, 28, 16, 19, 17, 23, 19, 16, 18, 18, 17, 20, 18,
  6.      21, 13, 11, 12, 13, 16, 13, 16, 10, 13, 14,  6, 19, 18, 19, 15,
  7.      17,  6, 14, 28, 15, 20, 16, 12)
  8.  
  9. # distance function
  10. dis_f <- function(t, q, i, j){
  11.   a <- (q[j]-q[i])/(j-i)
  12.   abs((q[i]*j-q[j]*i)/(j-i) + a * t - q[t]) / sqrt(a^2 + 1)
  13. }
  14.  
  15. pla <- function(q, i, j, time, eplison){
  16.   if (i > j || j - i <= 1)
  17.     return(sort(time))
  18.  
  19.   # find the maximum distance (Following two lines represents the Step 3~5)
  20.   dis_t <- dis_f((i+1):(j-1), q, i, j) # calculate distance of qi~qj
  21.   loc <- which.max(dis_t)
  22.   # find the position
  23.   pos <- i + loc
  24.   # record the position
  25.   best_so_far <- dis_t[loc]
  26.   # print the segment
  27.   cat(sprintf("segment: %i, %i, %.2f\n", i, j, best_so_far))
  28.   # Step 6: find more segments
  29.   if (best_so_far >= eplison)
  30.   {
  31.     # record the time
  32.     time <- c(time, pos)
  33.     if (pos < j)
  34.     {
  35.       time <- pla(q, i, pos, time, eplison)
  36.       time <- pla(q, pos, j, time, eplison)
  37.     }
  38.   }
  39.   return(sort(time))
  40. }
  41. # calculate eplison
  42. eplison <- sd(dis_f(1:length(q), q, 1, length(q)))
  43. time <- pla(q, 1, length(q), c(1, length(q)), eplison)
  44.  
  45. plot(1:length(q), q,type="o")
  46. lines(time, q[time], col = 2)
Advertisement
Add Comment
Please, Sign In to add comment