I'm trying to optimise the cost function for a simple pendulum on a cart. I have written the following code that returns the value of J(cost function) fobs2.m
function [J,u_candidate_fnc] =fobs2(lambda) sol=void(lambda(1),lambda(2),lambda(3),lambda(4)); t=0:0.001:4.452; u_candidate_fnc=candidate_fnc(t,lambda); J=(max(sol.y(1,:))-pi)^2+ abs(max(candidate_fnc)) + abs(max(sol.y(3,:)));
Candidate_fnc.m defines candidate function for acceleration of the cart as the input to the system.
function u=candidate_fnc(t,lambda) Tf=4.4520; w=2*pi/Tf; u1=lambda(1)*sin(w*t); u2=lambda(2)*sin(2*w*t); u3=lambda(3)*sin(3*w*t); u4=lambda(4)*sin(4*w*t); u5=(-5*lambda(1) -5/2*lambda(2)-5/3*lambda(3)-5/4*lambda(4))*sin(5*w*t); u=u1+u2+u3+u4+u5;
I used BVP solver to give me better trajectories using initial guesses. I've written the following code to store the new trajectories in sol. void.m:
function y=void(lambda1,lambda2,lambda3,lambda4) lambda=[lambda1 lambda2 lambda3 lambda4]; t_opt=linspace(0,4452*0.001,4452)'; solinit = bvpinit(t_opt,@xinit_fcn,lambda); sol = bvp4c(@system_odeset_fcn,@bc_function,solinit);
% disp('Lambda values: ') y=sol;
when I run fobs2.m it says, not enough input arguments in sol=void(lambda(1),lambda(2),lambda(3),lambda(4)); and Undefined variable "sol".
I had to get xinit_fcn from your https://www.mathworks.com/matlabcentral/answers/405238-how-to-resolve-interp1-error
I do not get any error about not enough input arguments when I invoke fobs2(lambda) . I do, however, run into problems with interp1 .
Your xinit_fcn is invoking interp1 with an x1_opt value derived from the t value that is passed into the function. However, bvpinit invokes the function with individual t values, not with the entire list of t values, so x1_opt will be a scalar. You are then trying to interp1(1 x 4452, 1 x 1, 1 x 1) . That fails because the second parameter must be the same length as the first parameter.
If you did have the entire original list of time values passed in, and were calculating x1_opt= -(pi/Tf)*All_t + pi and wanting to interpolate at the particular time, t, that was passed in to the xinit_fcn, then the result would always be the same as -(pi/Tf)*t + pi where t is the individual t. So it is not clear why you do not just have your xinit_fcn return -(pi/Tf)*t + pi .