I think your code interpret f, not as a function, but as an array with values. So, when you are trying to evaluate f(x), where x=2, your code looks for the second values in an array f.
Advice: 1) save your bound points in variables a and b (for example). Also create a proper function f (inline function or m-file function), so you can evaluate f in a and b. You will need a while or for+if to make your iterations.