2017-03-26 19 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]