matbox.de / Matlab

You're currently not logged in. You cannot access to all files. Why?

go back to Matlab-archive...

Matlab - singleserving function

This script demonstrates single-serving functions using anonymous functions.

% This code-snippets demonstrate how to create single-serving functions.
%
% (c)2010 by Torsten Reuschel, E-Mail: matlabhelp@fuesika.de
%
% This programs are free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

handle = getHandleSingleserve(true);

% actually running function, since we call it for the first time
handle(2) % ans = 4
% we call function, but it won't execute
handle(3) % no calculation performed
% filename: getHandleSingleserve.m
%
% The function gives back a function to calculate the square of a given value.
% The function is initialized with a flag that switches as soon as the function
% has been executed.

function h = getHandleSingleserve(reset);
    h = @(x)singleserve(x)

    function y = singleserve(x)
        if reset
            disp('running for first and last time');
            y = x*x;
            reset = false;
        end
    end
end

Notes on single-serving functions

Of course this way of using anonymous functions may be extended. For example you may define functions that run not just once, but two times before they deactivate themselves.