Question: 1. Use a for loop to evaluate the following sum, when x=.5. $$y = sum_{j=0}^{10} x^j$$ ```r{} y=0 # initialize y to 0 x= .5
1. Use a "for" loop to evaluate the following sum, when x=.5.
$$y = \sum_{j=0}^{10} x^j$$
```r{} y=0 # initialize y to 0 x= .5 for(i in 0:10) { y = y + x^i } print(y) ```
Your answer should be 1.999023.
(*5 points*)
2. Use a for loop, and the built in function "sqrt", to do the following:
loop over the elements of x=c(16,-9,9,4,-1,0) if the element x[i] is positive, print x[i] and the square root of x[i] or else if x[i] is negative, print("x[i] is negative")
```{r} x=c(16,-9,9,4,-1,0) #for ... { # if (condition ) {print(c(someting,sqrt(something)) # } else # {print message here}} # } ```
Your output should be equivalent to:
16 4 "x[i] is negative" 9 3 4 2 "x[i] is negative" 0 0
(*5 points*)
3. Use a "for" loop to iterate over the elements of a vector x, and increment a counter nodd when the element of x is odd. Then print the number of even and odd elements of x.
Recall that an integer y is odd if y%%2==1, and otherwise y is even.
Use the R commands below to generate a vector "x" of length 100.
```{r} set.seed(10) x=sample(1:10,100,replace=T) ```
Then modify the following code. ```{r} nodd=0 #initialize the counter nodd, which counts the number of odd elements of x # for ( ) {increment nodd in the loop when the associated element of x is odd} #neven= calculate neven using the length of x and nodd. paste("number of odd elements = ",nodd) #paste("number of even elements = ",neven) ``` For this vector x, the number of odd elements should be 56.
(*5 points*)
4. generate a random 5x5 matrix whose entries are the numbers 1,2, ... 25, but in random positions, using the following code: ```{r} set.seed(27) #set the seed for the random number generator x=matrix(sample(1:25), byrow=T,ncol=5) # x ```
On my system, I get the following input matrix:
[,1] [,2] [,3] [,4] [,5] [1,] 5 18 22 9 8[2,] 19 16 1 24 23
[3,] 17 25 3 11 21
[4,] 15 10 6 7 4
[5,] 13 20 14 12 2
If you have a different matrix, this is probably because you use a different version of R and a different random number generator. In that case, just use the following code to generate the matrix x:
```{r} xv <- c(5,18,22,9,8,19,16,1,24,23,17,25,3,11,21,15,10,6,7,4,13,20,14,12,2) x=matrix(xv, byrow=T,ncol=5) # x ```
Then, using a pair of nested for loops, loop over the positions in the matrix x, and if the associated element of x is odd, replace the element by its negative.
```{r} #for loop involving i { # for loop involving j { # x[i,j]=ifelse(x[i,j]%%2==1, -x[i,j], something here for odd # elements ) #}} #print(x) ```
Your answer should be equivalent to the following answer (which is valid for the input matrix shown above)
-5 18 22 -9 8 -19 16 -1 24 -23 -17 -25 -3 -11 -21 -15 10 6 -7 4 -13 20 14 12 2
(*5 points*)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
