create a function that increments a counter by 2 every time it is called in matlab

main.m
function count = incrementCounter()
% this function increments a counter by 2 every time it is called
persistent counter    % declare the counter as persistent so it retains its value between function calls
if isempty(counter)   % check if the counter is empty (i.e., on the first function call)
    counter = 0;      % initialize the counter to 0
end
counter = counter + 2; % increment the counter by 2
count = counter;       % set the output variable to the new counter value
end
482 chars
10 lines

To use this function, simply call incrementCounter() each time you want to increment the counter by 2. The function will retain the value of the counter between calls, so the counter will continue to increment each time you call the function.

gistlibby LogSnag