anonymous function for 'Events' to ode45
14 views (last 30 days)
Show older comments
Dear all
I use Matlab to teach Numerical Methods to second year physics students. When I show them the 'Events' functionality of ode45 (and related functions) they usually ask me if there is a way to declare the "event function" as an anonymous function. I have always answered negatively to this question, because it is not possible to return more than one variable for an anonymous function. Moreover, the solutions I usually find in forums are too complicated (¡even for me!). However, I have tried the solution I copy below and it has worked. My question is if this solution is correct enough to show to students or it works only in simple cases but may have in general an unexpected behaviour. It is a simple example: finding zeros, minima and maxima of a sine function.
% auxiliary function to unfold input to several output variables
f = @(varargin) varargin{:};
odefun = @(t,y) [y(2); -y(1)];
ef = @(t,y) f( [y(1), y(2), y(2)],[0 0 0],[0 1 -1]);
options = odeset('Events', ef);
sol = ode45( odefun, [0 2*pi],[0 1], options);
figure;
xg = linspace( 0, 2*pi, 100);
yg = deval( xg, sol);
plot(xg, yg(1,:),'-b',sol.xe, sol.ye(1,:),'or');
Thank you. Best regards
Carlos Soria-Hoyo Sevilla, SPAIN
0 Comments
Answers (2)
Walter Roberson
on 29 Oct 2017
You can do it directly:
ef = @(t, y) deal([y(1), y(2), y(2)],[0 0 0],[0 1 -1]);
I had not realized it was possible to return multiple values from an anonymous function until I saw someone post code with it about a year ago.
0 Comments
See Also
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!