Code covered by the BSD License  

Highlights from
Example: Using Nested Functions for Timers

Example: Using Nested Functions for Timers

by

 

08 Sep 2005 (Updated )

Example code from MATLAB News & Notes article on nested functions.

nested_callback_ex
function nested_callback_ex
% This example shows how to use a nested function to implement the callback
% of a timer object. Nested functions can be convenient for implementing
% callbacks because they have access to the workspace of their parent
% function.
%
% This example shows an image get progressively lighter every second for 10
% seconds. 

% Create and configure timer object
t = timer;
t.ExecutionMode = 'fixedRate';  % Run continuously
t.TasksToExecute = 10;          % Runs 10 times at default period of 1 second
t.TimerFcn = @MyTimerFcn;       % Run MyTimerFcn at each timer event

% Load and display a sample image
Im = imread('street1.jpg');
imagesc(Im)

% Start the timer
start(t)

    function MyTimerFcn(~,~)
        % MyTimerFcn    Sample timer callback function
        % The callback is automatically passed two input arguments. Since
        % we don't need them, we use ~ to ignore them.
        
        % Scale and display image
        Im = Im*1.1;                        % Make brighter
        imagesc(Im)                         % Display updated image
    end

end     % function nested_callback_ex

% Copyright 2005-2014 The MathWorks, Inc

Contact us