Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use an anonymous function as an event-function when solving an ODE in Matlab

Is it possible to use an anonymous function as an event function in Matlab. What I want to do is basically

opt = odeset('Events', @(t,y) (deal(y(end)-t^2,1,0)));
[T,Y] = ode45(@odefun,[tstart tend],y0,opt);

However, this returns an error complaining that the number of outputs to deal must be matched exactly. Is there some other way to make the anonymous function return multiple arguments?

like image 554
The input-validating guy Avatar asked Oct 21 '22 17:10

The input-validating guy


2 Answers

I noticed this post looking for the answer to the same question. This means that for some people the question may be still valid. Since finally I found the solution by myself, I'd like to give a little bit "outdated" answer.

Actually, yes - it's possible but not straightforward. Try this:

evnt_fun = @(t, f)subsref({'some stop condition', 1, 0}, struct('type', '{}', 'subs', {{':'}}));

I'm not able to fully check the backward-compatibility of the code. However, it works with R2011 and later MATLAB versions.

like image 106
Jacek Avatar answered Oct 27 '22 18:10

Jacek


No, you can't do it. Anonymous functions in Matlab only ever return one value.

Instead, you could define a thin wrapper around deal and pass your wrapper as a handle:

function [a b c] = wrapper(t,y)
    [a b c] = deal('some stop condition', 1, 0);
end

opt = odeset('Events', @wrapper);

[T, Y] = ode45(@odefun, [tstart tend], y0, opt);
like image 41
Chris Taylor Avatar answered Oct 27 '22 17:10

Chris Taylor