2015-11-01 147 views
-2

我希望這段代碼能夠工作,但是(t)的長度和w(t)的長度不同,所以它會阻塞我所有的代碼。我可以知道兩者如何具有相同的長度。如何限制函數的長度R

S(t)= S(0)exp(0.06t+0.20w(t)) #(1) 
    with S(0) =20 
    w(t) = standard Brownian movement 

    t <- seq(1,900,length=900) #the path or step=1 for 3 years (1y=300) 
    length(t) 
    v = matrix(rnorm(log(20)+0.06*t,sd=sqrt((0.20)^(2)*t)),nrow=5) 
    z = matrix(NA, ncol=900, nrow=5) 
    w = function(t) 
    {c(0,cumsum(v))} 
    length(w(t)) 
    Bn <-log(20)+ 0.06*t +0.20*w(t) 
    Br <- log(Bn) 
    plot(t,Br,type="l",xlab="Temps") 

    for (i in 1:5) # I need to draw 5 path of the function(1) 
    {z[i,] = c(0,cumsum(Br[i,]))} 
    dim(z) 
    u= apply(z,2,mean) #mean of the 5 path 

    plot(t,z[1,],xlab="temps",type="l",ylab="Brownian Movement") 
    for (i in 1:5){lines(t,z[i,])} 
    lines(t,u,lwd=2,col="red") 

謝謝您的時間

+0

哪個庫您使用? – vaettchen

+1

好吧,在這裏你在向量的開頭添加一個元素:'w = function(t) {c(0,cumsum(v))}'。因此,矢量是一個元素更長。 – Roland

+0

我改變了'w = function(t){c(cumsum(v))}'並且彈出另一個問題。顯然'Br [i,]'的尺寸不正確 –

回答

0

使用w= function(t){c(cumsum(v))},使所有的變量有900元。 Br只有一個維度,因此您必須使用Br[i]。這工作:

t <- seq(1,900,length=900) #the path or step=1 for 3 years (1y=300) 
length(t) 
v = matrix(rnorm(log(20)+0.06*t,sd=sqrt((0.20)^(2)*t)),nrow=5) 
z = matrix(NA, ncol=900, nrow=5) 
w = function(t) 
{c(cumsum(v))} 
length(w(t)) 
Bn <-log(20)+ 0.06*t +0.20*w(t) 
Br <- log(Bn) 
length(Bn) 
length(Br) 
plot(t,Br,type="l",xlab="Temps") 

for (i in 1:5) # I need to draw 5 path of the function(1) 
{z[i,] = c(cumsum(Br[i]))} 
dim(z) 
u= apply(z,2,mean) #mean of the 5 path 

plot(t,z[1,],xlab="temps",type="l",ylab="Brownian Movement") 
for (i in 1:5){lines(t,z[i,])} 
lines(t,u,lwd=2,col="red") 

enter image description here

+0

我明白了。但我希望boucle能夠爲整件事情做準備,因爲它重複了同樣的事情5次! –