How to use events in fminsearch
3 views (last 30 days)
Show older comments
I have a function I solve with ode45 which uses events. I need to minimise a parameter in this function and I am trying to use fminsearch to do so. But fminsearch uses optimset, which does not make use of event functions as far as I can tell. How can I make use of my event function inside of fminsearch so that I can minimise the parameters in my function?
0 Comments
Answers (1)
Ayush
on 4 Apr 2024
Hi,
One workaround you can try to integrate the use of an event function within "fminsearch" while solving an ODE using "ode45" is to encapsulate the call to "ode45", including the event handling, within the objective function that you pass to "fminsearch". The event function can be used to stop the integration based on certain conditions, and the outcome can influence the value returned by the objective function, which "fminsearch" will attempt to minimize.
Refer to the below pseudo code for better understanding:
% Initial guess for the parameter to be optimized
initialParams = ...;
% Set options for fminsearch if necessary
options = optimset('Display', 'iter', 'TolX', 1e-6, 'TolFun', 1e-6);
% Call fminsearch
[optimalParams, fval] = fminsearch(@objectiveFunction, initialParams, options);
% Display the optimal parameters
disp('Optimal Parameters:');
disp(optimalParams);
%%%%%% Defining objective function %%%%%%
function cost = objectiveFunction(params)
% Set options for ode45 to use the event function
options = odeset('Events', @myEvent);
% Solve the ODE with ode45
[T, Y, TE, YE, IE] = ode45(@(t, y) myODE(t, y, params), [t0 tf], y0, options);
% Define your cost function based on the ODE solution
% For example, the cost could be related to the final state, time at an event, etc.
cost = ...; % Define how the solution affects the cost
end
%%%%%% Defining ODE function %%%%%%
function dydt = myODE(t, y, params)
% Example ODE function
dydt = ...; % Define your ODE using parameters and variables
end
%%%%%% Defining Event function %%%%%%
function [value, isterminal, direction] = myEvent(t, y)
% Example event function
value = ...; % Condition to trigger the event
isterminal = 1; % Stop the integration when the event is triggered
direction = 0; % The zero indicates that all zeros are to be found
end
"odeset" is used to specify an event function that "ode45" should use during the integration process. For more information on the "odeset", refer to the below documentation:
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!