问题描述
我运行一个循环:
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))
}
但是,Vt10
最终仅输出10个结果(i = 0
时不包括第一次迭代).如何创建一个包含所有11个迭代的向量?
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?
推荐答案
答案:
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))
}
此外,您还需要Vt10[i+1]
,因为您从0循环到10,而数组索引应该是1到11.
Also, you need Vt10[i+1]
, because you loop from 0 to 10, while array index should be 1 to 11.
评论:
您的代码看起来像C代码.不仅您从0开始索引,而且为此任务编写了一个循环.
Your code looks like C code. Not only you start index from 0, but also you write a loop for this task.
尝试:
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))
在这种情况下,无需预先定义向量. R知道您正在执行逐元素计算,并且会自动为Vt10
分配一个长度为11的向量.
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
.
这篇关于将循环结果保存在向量R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!