« Earlier2 items total Later »

Simple objects with nested functions

You can create simple reference objects using nested functions and matlab structures.

function obj = counter(c1)

   obj.decr = @decr;
   obj.incr = @incr;

   function c1 = incr
       c1 = c1 + 1;
   end

   function c1 = decr
       c1 = c1 - 1;
   end

   function c1 = get
   end

end


You can then use the returned structure to access the counter
object

% create the counter
c = counter(10);

% increment;
c.incr();
c.incr();

% decrement;
c.decr();

% get the value
c.get()
ans =
     11

Nested Function Counter

Nested function are a powerfull way of creating mini objects that maintain their own state. The most basic example most often given is that of creating a counter.

function h = create_counter(x)
   h = @nest_count;
   count = x

   function count = nest_count
      count = count + incr
   end
end


and can be used like this


>> counter = create_counter(5);
>> counter()
ans =
      6

>> counter();
ans = 7

>> counter2 = create_counter(5);

>> counter2()
ans = 6

>> counter()
ans =
      8



As can be seen each counter function maintains it's own
counter variable.

« Earlier2 items total Later »




Sponsored by

Sole Central

Your one stop shop for Birkenstock and Crocs shoes and sandles.