2017-03-26 22 views
0

我写下面的函数R:非顺应性参数,错误时优化

costFunc=function(par,dat){ 
    state=sapply(mySamp,stateofMC,windDat=windDat) 
    sum=0 
    for(i in 1:3){ 
     state_loc=which(state==i) 
     state_dat=dat[state_loc,,drop=F]  # m x 4 matrix 
     state_coef=rbind(-par,1)[,i,drop=F] # 4 x 1 matrix 
     state_prod=state_dat %*% state_coef # m x 1 matrix 
     sum = sum + colSums(abs(state_prod)) 
    } 
    return(sum) 
} 

它工作时,我的一些值插入自定义功能;但未能当我试图优化它,提供以下错误消息:

forecstCoef=optim(par=tranProb,costFunc,gr=NULL, dat=dat, 
      method="Nelder-Mead")$par 

Error in state_dat %*% state_coef : 
non-conformable arguments 

我检查类state_dat和state_coef的,它们都输出矩阵。

回答

0

不知何故似乎在线路中发生错误:
state_coef=rbind(-par,1)[,i,drop=F]
它把par作为载体代替基体,desipte在optim的初始值是一个矩阵。它适用于以下修改:

state_coef=rbind(-matrix(par,nrow=3),1)[,i,drop=F]