create a function that increments a global counter every time called in matlab

To increment a global counter every time a function is called in MATLAB, you can follow these steps:

  1. Define a global variable in the main workspace.
main.m
global counter
counter = 0;
28 chars
3 lines
  1. In your function, declare the global variable using the global keyword.
main.m
function myFunction()
    global counter
    counter = counter + 1;
end
72 chars
5 lines
  1. Call the function multiple times to increment the global counter.
main.m
myFunction()
myFunction()
disp(counter) % Output: 2
52 chars
4 lines

The global keyword allows the function to access the global variable counter and increment it every time the function is called.

gistlibby LogSnag