Reputation: 131
I run a loop:
N = 10
alpha = 0.05
sigma = 0.01
for (i in 0:N){
Vt10[i] = ((sigma^2)/(alpha^2))*((N-i)+(2/alpha))*exp(-alpha*(N-i))-(1/(2*alpha))*exp(-2*alpha*(N-i))-(3/(2*alpha))
}
However, Vt10
eventually outputs only 10 outcomes (doesn't include the first iteration, when i = 0
). How can I create a vector that would include all 11 iterations?
Upvotes: 0
Views: 647
Reputation: 73265
Answer:
N = 10
alpha = 0.05
sigma = 0.01
Vt10 = numeric(11) ## this!
for (i in 0:N){
Vt10[i+1] = ((sigma^2)/(alpha^2))*((N-i)+(2/alpha))*exp(-alpha*(N-i))-(1/(2*alpha))*exp(-2*alpha*(N-i))-(3/(2*alpha))
}
Also, you need Vt10[i+1]
, because you loop from 0 to 10, while array index should be 1 to 11.
Comment:
Your code looks like C code. Not only you start index from 0, but also you write a loop for this task.
Try:
N = 10
alpha = 0.05
sigma = 0.01
i = 0:10
Vt10 = ((sigma^2)/(alpha^2))*((N-i)+(2/alpha))*exp(-alpha*(N-i))-(1/(2*alpha))*exp(-2*alpha*(N-i))-(3/(2*alpha))
In this situation, there is no need to predefine a vector. R knows you are performing element-wise computation, and will automatically assign a length-11 vector for Vt10
.
Upvotes: 2