2014-02-12 72 views
0

我有3矩陣被組合成一個3D矩陣。我必須找到這樣的概率,使隱藏序列's'的值與P.中的矩陣值之一相匹配。試圖「obssim」R矩陣的概率誤差

P1=cbind(c(1,2,3,4),c(1,2,3,4),c(1,2,3,4),c(1,2,3,4)) 
P2=cbind(c(1,2,3,4),c(1,2,3,4),c(1,2,3,4),c(1,2,3,4)) 
P3=cbind(c(1,2,3,4),c(1,2,3,4),c(1,2,3,4),c(1,2,3,4)) 

P=array(c(P1,P2,P3),c(4,4,3)) 

hssim=function(n,lambda) 
{ 
     r=dim(lambda)[1] 
     states=1:r 
     s=vector("numeric",n) 
     pi.lam=equil(lambda) 
     s[1]=sample(states,1,FALSE,pi.lam) 
     for (t in 2:n) { 
       s[t]=sample(states,1,FALSE,prob=lambda[s[t-1],]) 
     } 
     s 
} 

lambda=rbind(c(1,2,3),c(4,5,5),c(6,7,8)) 
s=hssim(10000,lambda) #(gives a hidden sequence) 
obssim=function(s,P) 
{ 
     n=length(s) 
     r=dim(P)[3] 
     q=dim(P)[2] 
    states=1:q 
     obs=vector("numeric",n) 
     for (t in 1:n) { 
     obs[t]=sample(states,1,FALSE,prob=P[,s[t],]) 
     } 
     obs 
} 

我得到一個錯誤的最後一個編碼區的一個錯誤,當調用「OBS」,無法解決解決它成功:

obs=obssim(s,P) 

Error in sample(states, 1, FALSE, prob = P[, s[t],]) : 
    incorrect number of probabilities 
+0

什麼是'hssim'功能'equil' ?這是來自一些包嗎? – Zbynek

+0

角球面上是平衡的概率的函數: 角球面上=函數(P){ E =本徵(T(P))$載體[1] E /總和(E) } – user3301661

+0

我看到,但是從該包?它不是基本R安裝的一部分。 – Zbynek

回答

0

的問題是,你傳遞的參數prob是一個4x3的矩陣,而對象states,你選擇的是四個元素的矢量。

> states 
[1] 1 2 3 4 
> P[,s[1],] 
    [,1] [,2] [,3] 
[1,] 1 1 1 
[2,] 2 2 2 
[3,] 3 3 3 
[4,] 4 4 4 

prob長度應該是相同的如功能samplex長度。我想,服用第一(或任何,因爲它們是同一個),該矩陣的列就足夠了

# replace line starting with obs[t] <- ... 
obs[t]=sample(states,1,FALSE,prob=P[,s[t],1]) 

比,代碼運行沒有錯誤