MATLAB: The efficiency of recursion in MATLAB

memoizationmemoryrecursion

I wanted to implement an algorithm I wrote with a recursion loop. At first I got an ERROR saying that I ran ran out of memory, and after working on saving memory, I got a messege saying that the default maximum for MATLAB is a recourse of 500 steps.
Are there ways to improve using recursion without chopping important data, or risking crashing your computer?
Matar Maoz

Best Answer

Many recursive algorithms are actual terrible wastes of time and memory. You end up computing and recomputing the same thing many times. Instead, look for memoization schemes, that avoid the recomputations by saving those values. For example, look at the Fibonacci sequence.
F(n+1) = F(n) + F(n-1)
Suppose we compute F(5), by calling recursively for the values of F(4) and F(3). Then F(4) is gotten as the sum of F(3) + F(2), but F(3) is the sum of F(2)+F(1), etc. In the end, we can see that many of these terms will have been accessed multiple times.
The point is, while recursion seems an elegant solution, it is in reality a terrible solution here if you simply do the direct recursive calls.