Skip to content

If-statement in for-loop

2 messages · gncl dzgn, Gerrit Eichner

#
Hello, "gncl dzgn",

your problem has a flavor of homework which is usually not delt with on 
this list. However, a few comments:

0. The description of your problem is rather vague, in particular, the 
meaning of "input" in the description of your "conditions" is unclear! (By 
the way, your main problem is probably not the inclusion of the 
conditions; see 2.)

Note: "PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html and provide commented, 
minimal, self-contained, reproducible code."
^^^^^^^

1. Do not use variable names like t, T, c, s because they already exist as 
R-objects.

2. Have you noticed the warnings "In s >= d : longer object length is not 
a multiple of shorter object length" and "In s + b * (0:T) : longer object 
length is not a multiple of shorter object length"? Apparently the 
involved objects (s, d, b and T) do not "fit together". Hint: Compare the 
lenght of s with the lengths of d and 0:T!

3. Do not run the code all at once, but either without the for-loops line 
by line with j and i set to approriate values (like i = 1 and j = 2), or 
with the for-loops, but with N and T very small, e. g. N = 1 and T = 2 to 
start with. Alternatively, you could also take a look at the function 
browser() (and include it in the bodies of your for-loops).

4. Another hint: Your if-else-statement

   if(x < minx) {
     s[i] <- minx
    } else {
     if(x > maxx) {
       s[i] <- maxx
      } else s[i] <- x
    }

appears be simplifiable to

   s[i] <- min( max( x, minx), maxx)


  Hth  --  Gerrit