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: 
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.
I can supplement a bit more information about how we proceed after writing the function above. We then define, say:

```
tspan = [0 6];
z0 = [0, 5*cos(pi/4), 0, 5*sin(pi/4)];
options = odeset('events','on');
[t y] = ode42('proj',tspan,z0,options)

```

By writing this the output is 5 columns, 1 column for `tspan` , and 1 column for each of the z-values (`z(1)`, `z(2)`, `z(3)` and `z(4)`). When `z(3)` hits zero, the calculations are terminated since the "event" occurs.

If, on the other hand I do not include the `options = odeset('events','on')` line, and simply write:

```
[t y] = ode42('proj',tspan,z0)

```

The calculations are performed for the entire `tspan` range. 

Yet, I still fail to see how `ode42` is capable of calculating all the output vectors when we activate "events" since it then looks logical me that MatLab should only execute the "else"-statement in the "proj"-function. And in this part of the function, the actual system of the differential equations is not included.