Reputation: 25
Let's say I have a vector v with elements 1...n, and I know that v(1) = v_0, and then
v(i+1) = 1/(a*v(i) + b).
This is straightforward to implement using either a single for loop, or recursion. Recursion is a terrible idea in Matlab, and the single foor loop is still not optimal if possible. Can I vectorize such a operation?
And to make this post more useful, is there a general way to vectorize
v(i+1) = f(v(i)),
where f(x) is an arbitrary function? What about something like
v(i+1) = a(i)*v(i) + b(i)
where a, and b are now vectors.
Upvotes: 1
Views: 1363
Reputation: 14937
A for
loop is not as bad in MATLAB as it used to be, due to just-in-time compilation. When in doubt, just write the loop and continue with your work. Unless your vectors are gigantic, the loop won't bother you in the slightest. If (and only if) the loop is a bottleneck, go back and try silly MATLAB tricks to optimize.
In a specific answer to your question, no, I do not believe there's a generic way to express v(i+1) = f(v(i)). You could easily write one using a function handle, but the performance would be something less than just open-coding the expression.
Upvotes: 2