将参数方程拟合到数据

时间:2017-03-03 05:46:43

标签: r curve-fitting parametric-equations

我将使用我的数据实现此方法。 Fitting known equation to data。 我怎么能有不同的x区间的6个不同的方程式。

以下是我用来拟合方程的函数

Func <- function(t,t1,t2,t3,t4,t5,t6,a1,a2,a3,a4,a5,a6,b1,b2,c1,c2,c3,c4,c5,c6){
  if(t<t1){
    t*0
  }
  else if(t>=t1&t<t2){
    a1*t+c1
  }
  else if(t>=t2&t<t3){
    a3*t+c2
  }
  else if(t>=t3&t<t4){
    a3*t+c3
  }
  else if(t>=t4&t<t5){
    a4*t**2 + b1*t+c4
  }
  else if(t>=t5&t<t6){
    a5*t**2 + b2*t+c5
  }
  else if(t>=t6){
    a6*t+c6
  }
}


plot(t,w)
curve(Func(t,1.4,14.4,41.8,60.3,194.3,527,0.0022,0.0029,0.0016,0.00001,0.00001,0.0168,0.0001,-0.0006,0.0063,-0.0433,-0.0022,0.00408,0.2337,-5.3732),add=TRUE)

执行曲线功能时,我收到错误:

Error in curve(Func(t, 1.4, 14.4, 41.8, 60.3, 194.3, 527, 0.0022, 0.0029,  : 
  'expr' must be a function, or a call or an expression containing 'x'

1 个答案:

答案 0 :(得分:1)

curve需要向量化函数,而if不会向量化。您可以使用ifelse,但使用它可以更有效和高效,R可以通过将它们强制转换为0/1来在计算中使用布尔值。

Func <- function(t,t1,t2,t3,t4,t5,t6,a1,a2,a3,a4,a5,a6,b1,b2,c1,c2,c3,c4,c5,c6){
  (t<t1) * t * 0 +
  (t>=t1&t<t2) * (a1*t+c1) +
  (t>=t2&t<t3) * (a3*t+c2) +
  (t>=t3&t<t4) * (a3*t+c3) +
  (t>=t4&t<t5) * (a4*t**2 + b1*t+c4) +
  (t>=t5&t<t6) * (a5*t**2 + b2*t+c5) +
  (t>=t6) * (a6*t+c6)
}


t <- (1:10000)/10
plot(t, t/100)

#you must use x here    
curve(Func(x,1.4,14.4,41.8,60.3,194.3,527,0.0022,0.0029,0.0016,0.00001,0.00001,0.0168,
               0.0001,-0.0006,0.0063,-0.0433,-0.0022,0.00408,0.2337,-5.3732),add=TRUE)

resulting plot