BEWARE!!! using nested functions is a nice approach to emulate oop, but there is a number of problems associated with their use in Matlab:
1. Nested functions are not automatically garbage collected by Matlab, you should do it manually otherwise you Matlab session would be getting slower and slower We always define a method DISPOSE for each object, and call it when an object needs to be destroyed, it looks like
function public_dispose()
vars = who; clear(vars{:});
end
2. You should not have cyclic dependences between several objects, e.g. define a tree where node objects have fields this.parent and this.children with parent and children fields containing (pointing to) other node objects. If you have such cyclic dependencies in your code and call any method on the node object your performance will go to zero. It seems that Matlab tries to update all fields and when fields are objects then it updates these objects altogether and so originates a recursion.
Another point is that it is a good practice to have only one variable (of type struct) in the nested scope, for example call it *this* (like in java) and store all object data in the fields of *this*
Please allow me to retract the last sentence of my previous comment: the code here has a twist that's not in Michael Corvin's examples. In any case, I would definitely recommend examining this submission.
1. If a closure is a 'function that has privately captured variables from an enclosing scope', then a nested function fits the bill, and there is no need to bring in persistence, which is the focus of your example.
2. Responding to a question about the added benefits of this approach compared to the use of 'persistent' by saying that 'closures are a more general and powerful abstraction' is not very helpful.
3. It's persistence, and the backdoor way of creating *objects* that apparently is available in Matlab, that are the revelation/shocker here. Thank you for providing the link to Loren Shure's blog entry; I would recommend everyone to follow the link, and go directly to the illuminating comments (#3 and #6) by Michael Corvin. Michael's sample code shows everything that this submission does, and more.
The "persistent" built-in would be able to achieve the same functionality as the example, but closures are a more general and powerful abstraction.
Closures are available in languages like Python, Ruby, LISP, Scheme, and Javascript. For the most part, they are not available (or aren't fully implemented) in languages like C, C++, and Java.
To learn more about other things you can do with closures, I encourage you to visit the following sites (that explain things more thoroughly than I can):