need help, i am having trouble in the inner loop because it is not exectuted completed, it only give me the value of c and s only 5 times not 100.

...sg=1
del=3
L=2.814
mu0=0
s0=0
k=0.5
h=4
K=k*sg
H=h*sg
r=c()
mu=mu0+del*sg
lamda=0.10
c=c()
s=c()
for(j in 1:1000){
for(i in 1 :1000){
x=rnorm(1,mu,sg)
if(i==1){
c[1]=abs((x-mu0+0))
if(c[i]>K){
s[i]=(0+x-mu0)*(1-K/c[i])
}
else
{
st=0}}
else{
c[i]=abs(x-mu0+s[i-1])
if(c[i]>K){
s[i]=(s[i-1]+x-mu0)*(1-K/c[i])
}
else
{
st=0}}
if(s[i]>H|s[i]<(-H)){
r[j]=i;break;
}
}
}
mean(r)

Hello, I'm afraid I find your code hard to follow.
you use many small variable names, the meaning is impossible to guess, so conceptually what you are trying to do is hard to follow. Context is always helpful. Data also.
I would caution you against using variable names like c, because as you've seen c() is an often used function, its easy to get confused when reading and writing such code.

There is a useful package called 'styler' that you could install, it enabled me to somewhat style your code with just a button press. read about it here : https://github.com/r-lib/styler

the result :

...sg=1
del <- 3
L <- 2.814
mu0 <- 0
s0 <- 0
k <- 0.5
h <- 4
K <- k * sg
H <- h * sg
r <- c()
mu <- mu0 + del * sg
lamda <- 0.10
c <- c()
s <- c()
for (j in 1:1000) {
 for (i in 1:1000) {
   x <- rnorm(1, mu, sg)
   if (i == 1) {
     c[1] <- abs((x - mu0 + 0))
     if (c[i] > K) {
       s[i] <- (0 + x - mu0) * (1 - K / c[i])
     }
     else {
       st <- 0
     }
   }
   else {
     c[i] <- abs(x - mu0 + s[i - 1])
     if (c[i] > K) {
       s[i] <- (s[i - 1] + x - mu0) * (1 - K / c[i])
     }
     else {
       st <- 0
     }
   }
   if (s[i] > H | s[i] < (-H)) {
     r[j] <- i
     break
   }
 }
}
mean(r)

thanks alot for your kind help!

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

I further analysed your code.
Your conditions towards the bottom, which can cause the break; that you have, are breaking always before i>5 and as the c vector is only extended by c[i] <- style assignments, its not growing larger than 5