Optimize cost function to obtain optimal value of the optimization variable.

The problem is to find a and b such that the cost function is minimized. The cost function is defined as,
The dynamical equations are:
I tried to use the ode45 to solve the the dynamical equations but was unable to solve using the ode45 as it has a and b also as variables, which are needed to optimize the cost function. Can someone help to solve the equations by ode45 and minimize the cost function at the same time? I am trying to use fminsearch but how to use it?

 Accepted Answer

Create a function that accepts a and b and uses ode45() to run the system to tspan 10. Return the values of y1(end) and y2(end) for those particular a and b
Now write a caller to that function that accepts a vector of two values, a and b, runs the function mentioned above, calculates C and returns the value.
Now use fminunc() or fmincon() on that second function. The vector of coordinates that minimizes the function will be the a and b values you are looking for.

3 Comments

[t,y]=ode45(@(t,y) ques1(t,y,a,b), [0 10], [1,2]')
Unrecognized function or variable 'a'.

Error in solution (line 1)
[t,y]=ode45(@(t,y) ques1(t,y,a,b), [0 10], [1,2]')

Error in odearguments (line 92)
f0 = ode(t0,y0,args{:}); % ODE15I sets args{1} to yp0.

Error in ode45 (line 107)
odearguments(odeIsFuncHandle,odeTreatAsMFile, solver_name, ode, tspan, y0, options, varargin);
plot(t,y(:,1),'-o',t,y(:,2),'-o')
function dydt = ques1(t,y,a,b)
dydt = [cos(a+b*t)-sin(y(2));(1/y(1))*(sin(a+b*t)-cos(y(2)))];
end
How to define a and b? I have to find a and b so we can not define it at the start.
init_ab = [0 1];
best_ab = fminunc(@cost_ab, init_ab);
a = best_ab(1); b = best_ab(2);
function cost = cost_ab(ab)
[t,y]=ode45(@(t,y) ques1(t,y,ab(1),ab(2)), [0 10], [1,2]');
cost = (y(end,1) - 1500).^2 + (y(end,2) - pi/2).^2;
end
init_ab = [0 1];
[best_ab,cost] = fminunc(@cost_ab, init_ab)
Local minimum possible. fminunc stopped because it cannot decrease the objective function along the current search direction.
best_ab = 1×2
0.8611 -0.1213
cost = 2.1954e+06
a = best_ab(1); b = best_ab(2);
function cost = cost_ab(ab)
ques1 = @(t,y)[cos(ab(1)+ab(2)*t)-sin(y(2));(sin(ab(1)+ab(2)*t)-cos(y(2)))/y(1)];
[t,y]=ode45(ques1, [0 10], [1,2]');
cost = (y(end,1) - 1500).^2 + (y(end,2) - pi/2).^2;
end

Sign in to comment.

More Answers (0)

Products

Release

R2020a

Community Treasure Hunt

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

Start Hunting!