We have been given a task, which we just can't figure out:
Write an R function which will generate a vector containing the first n terms of the Fibonacci sequence. The steps in this are as follows: (a) Create the vector to store the result in. (b) Initialize the first two elements. (c) Run a loop with i running from 3 to n, filling in the i-th element
Work so far:
vast=function(n){
vast=vector()
vast[1]=1
vast[2]=1
for(i in 3){vast[i]=vast[i-1]+vast[i-2]}
}
All we end up is with the error: object of type 'closure' is not subsettable ??
How are we supposed to generate the wanted function?
My vote's on closed form as @bdecaf suggested (because it would annoy your teacher):
vast = function(n) round(((5 + sqrt(5)) / 10) * (( 1 + sqrt(5)) / 2) ** (1:n - 1))
But you can fix the code you already have with two minor changes:
vast=function(n){
vast=vector()
vast[1]=1
vast[2]=1
for(i in 3:n){vast[i]=vast[i-1]+vast[i-2]}
return(vast)
}
I would still follow some of the suggestions already given--especially using different names for your vector and your function, but the truth is there are lots of different ways to accomplish your goal. For one thing, it really isn't necessary to initialize an empty vector at all in this instance, since we can use for
loops in R to expand the vector as you were already doing. You could do the following, for instance:
vast=function(n){
x = c(1,1)
for(i in 3:n) x[i] = x[i-1] + x[i-2]
return(x)
}
Of course, we all have things to learn about programming, but that's why we're here. We all got help from someone at some point and we all get better as we help others to improve as well.
UPDATE: As @Carl Witthoft points out, it is a best practice to initialize the vector to the appropriate size when that size is known in order save time and space, so another way to accomplish this task would be:
vast=function(n) {
x = numeric(n)
x[1:2] = c(1,1)
for(i in 3:n) x[i] = x[i-1] + x[i-2]
return(x)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With