Question: In my textbook I have encountered an example of a function I am supposed to use when specifying an event location for a system of ODEs. The function example is as follows:

```
function [value, isterminal, dircn] = proj(t,z,flag);
g = 9.81;
if nargin < 3 | isempty(flag)
    value = [z(2); 0; z(4); -g];
else
    switch flag
        case 'events'
            value = z(3);
            isterminal = 1;
            dircn = -1;
        otherwise
            error('function not programmed for this event');
    end
end

```

There is one part of the logic here which I don't understand. Say that I activate the "events" option and then run ode45. How, then, can ode45 actually read the system of equations (which is specified in the above function as `value = [z(2); 0; z(4); -g];`)? I have ran ode45 based on the above function, after specifying tspan and inital conditions of course, and it works like a charm. But I don't understand how ode45 can read the system properly when it is only presented in the "if"-part of the script above.

If anyone can explain the logic here, I would greatly appreciate it!

Answer: 
Well I think I can explain some parts. As I wrote above it is strange that the dimension of `value` changes.

given your statespace and the names of your variables it looks like 2 dimensional motion.

in the case of no flag it seems that state space is:

1. horizontal position (x)
2. horizontal speed (vx)
3. vertical position (y)
4. vertical speed (vy)

**correction**
It seems that ode can send `'events'` when you specify them. So your function outputs 3rd component of the state space. Look at this site explaining it: <http://www.mathworks.de/help/techdoc/math/f1-662913.html>

unless you specify it beforehand ode can't send `'events'` to the function so this part will not be called. 

But your function won't work anyway - as the derivative would need to have same dimension as the statespace (4x1). But has only 1x1.

But I really don't know what you mean by "specifying an event location". Maybe the secret is hidden there.

With some creativity I think you could use the function to extract the 3rd component of the state space.
The answer is in the `if` command:

```
if nargin < 3 | isempty(flag)
    value = [z(2); 0; z(4); -g];
else

```

If number of arguments is less than 3 or if variable `flag` is empty, then set variable `value` to `[z(2); 0; z(4); -g]`. Otherwise, if variable `flag` is `'events'`, then set variable `value` to `z(3)`, and when `flag` is not `'events'`, report an error. So this function always assigns some return value for variable `value` or, reports an error using `error` command.