anonymous function for 'Events' to ode45

조회 수: 16 (최근 30일)
Carlos Soria-Hoyo
Carlos Soria-Hoyo 2017년 10월 29일
답변: Carlos Soria-Hoyo 2017년 10월 30일
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

답변 (2개)

Walter Roberson
Walter Roberson 2017년 10월 29일
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.

Carlos Soria-Hoyo
Carlos Soria-Hoyo 2017년 10월 30일
Thank you for your answer.
Function deal does not work for this application. I saw it in a post at stackoverflow
Regards.
Carlos
I get the following output:
Error using deal (line 37)
The number of outputs should match the number of inputs.
Error in @(t,y)deal([y(1),y(2),y(2)],[0,0,0],[0,1,-1])
Error in odeevents (line 28)
eventValue = feval(eventFcn,t0,y0,eventArgs{:});
Error in ode45 (line 147)
[haveEventFcn,eventFcn,eventArgs,valt,teout,yeout,ieout] = ...
Error in prueba (line 7)
sol = ode45( odefun, [0 2*pi],[0 1], options);

카테고리

Help CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by