Reputation: 43
I am really sorry if this is a silly question, but I am very new to netlogo and suggestions I find elsewhere do not seem applicable to my case; the question is:
how do I store and print all values of a variable from a repeat loop in netlogo?
let x 1
let y 1
let i n - 2
repeat i [let z (x + y) set x y set y z ]
let list1 (list x y)
print list1`
this code is now making and printing a list that contains only the last two values of x and y - how can I make it save and print all values that x and y had within the loop?
I am really sorry again
Upvotes: 2
Views: 193
Reputation: 3806
If you just want to calculate the fib sequence and get the numbers in a list, you may want to consider this. I'd like to note that your list of xs and list of ys are subsets of the fib sequence.It's an alternative to the recursive case mentioned by Alan and it's a bit more cleaner than the repeat statement:
to-report fib [n]
if n < 2 [ report n-values (n + 1) [?]] ;; consider base case
report reduce [sentence ?1 ((last ?1) + (last (but-last ?1))) ] (fput (list 0 1) (n-values (n - 1) [?]))
end
Upvotes: 1
Reputation: 9620
to test-fib [#n]
let x 1
let y 1
let xs (list x)
let ys (list y)
let i (#n - 2)
repeat i [
let z (x + y)
set x y
set y z
set xs lput x xs
set ys lput y ys
]
print xs
print ys
end
But it would be preferable to use a reporter. Assuming you want at least two items:
to-report better-fib [#n]
let x_2 0
let x_1 1
let fibs (list x_2 x_1)
repeat (#n - 2) [
let x (x_2 + x_1)
set fibs (lput x fibs)
set x_2 x_1
set x_1 x
]
report fibs
end
And it might be fun to use a little recursion:
to-report fun-fib [#n]
if (#n = 0) [report []]
if (#n = 1) [report [0]]
if (#n = 2) [report [0 1]]
let f1 (fun-fib (#n - 1))
let x_1 last f1
let x_2 last butlast f1
report lput (x_2 + x_1) f1
end
You can always drop the initial items if you don't want them.
Upvotes: 3