2017-06-04 100 views
0

以下代碼塊用於定義和集成涉及矩陣指數的函數f1。將函數集成在R中時出現錯誤

library(expm) 
Lambdahat=rbind(c(-0.57,0.21,0.36,0,0), 
c(0,-7.02,7.02,0,0), 
c(1,0,-37.02,29,7.02), 
c(0.03,0,0,-0.25,0.22), 
c(0,0,0,0,0)); 

B=rbind(c(-1,1,0,0,0),c(0,0,0,0,0),c(0,0,0,0,0),c(0,0,0,0,0),c(0,0,0,0,0)) 

f1<-function(tau1) 
{ 
    A=(expm(Lambdahat*tau1)%*%B%*%expm(Lambdahat*(5-tau1))); 
    return(A[1,5]); 
} 

out=integrate(f1,lower=0,upper=5)#integration of f1 

在上面的行的集成提供了以下錯誤:

Error in integrate(f1, lower = 0, upper = 5) : 
evaluation of function gave a result of wrong length 
In addition: Warning messages: 
1: In Lambdahat * tau1 : 
longer object length is not a multiple of shorter object length 
2: In Lambdahat * (t[i] - tau1) : 
longer object length is not a multiple of shorter object length 

要檢查,如果函數輸出和輸入是函數f1不同的長度,10級均勻地間隔開的輸入和f1的相應的輸出的報道如下。輸入和輸出長度所有的測試用例記錄爲等於1

sapply(X=seq(from=0,to=5,by=0.5),FUN=f1) 
[1] 2.107718e-01 1.441219e-01 0.000000e+00 2.023337e+06 1.709569e+14 
[6] 1.452972e+22 1.243012e+30 1.071096e+38 9.302178e+45 8.146598e+53 
[11] 7.197606e+61 

如果任何人都可以分享任何暗示或指示,其中的代碼可能會錯誤的,那將是非常有益的。非常感謝!

回答

1

問題是傳遞給integrate的函數需要被矢量化,即它應該能夠接收一個輸入值向量並返回一個輸出值向量。我認爲f1 <- Vectorize(f1)可以解決你的問題。

+0

非常感謝你,是的,它解決了問題。謝謝! – user168826

+0

@ user168826不客氣! – Consistency

相關問題