function [J_val,exitflag,mv] = fcn(x_ref, x_prev, u_prev,param,lb, ub,Ts_mpc, Nc, N,Q, R,Ref)
options = optimoptions('fmincon', 'Display', 'none','Algorithm','sqp');
cost = @(u_0) Cost_fun(u_0,x_prev,x_ref,param,Ts_mpc,N,Q,R,Ref);
[u_sol, J_val, exitflag] = fmincon(cost, u_0, [], [], [],[], lb, ub,[], options);
function x_next = predictor(u_0,x_prev,param,Ts_mpc,kappa)
ye_dot = w-(vs*cos(ye)/(1-CTE*kappa))*kappa;
v_dot = (r_wheel*(T_L + T_R - L_OC*m_body*r_wheel*w^2))/(2*I_w + m_body*r_wheel^2 + 2*m_w*r_wheel^2);
w_dot = (r_wheel*(L_w*T_R - L_w*T_L + L_OC*m_body*r_wheel*w*v_cm))/(2*I_w*L_w^2 + I_body*r_wheel^2 + 2*I_m*r_wheel^2 + L_OC^2*m_body*r_wheel^2 + 2*L_w^2*m_w*r_wheel^2);
S_dot = vs*cos(ye)/(1-CTE*kappa);
CTE_next = CTE + Ts_mpc*CTE_dot;
ye_next = ye + Ts_mpc*ye_dot;
S_next = S + Ts_mpc*S_dot;
v_next = vs + Ts_mpc*(v_dot+w_dot*L_OS_y1);
w_next = w + Ts_mpc*w_dot;
x_next = [CTE_next;ye_next;S_next;v_next;w_next;dv_next;dw_next];
function J = Cost_fun(u_0,x_prev,x_ref,param,Ts_mpc,N,Q,R,Ref)
j = find(S>=Ref(:,9),1,'last');
x_ref = [0;0;Ref(j,9);Ref(j,10);Ref(j,11);0;0];
x_next = predictor(u_0,x_prev,param,Ts_mpc,kappa);
x_e = [x_next(1);x_next(2);x_ref(3) - x_next(3);x_ref(4) - x_next(4);x_ref(5) - x_next(5);x_next(6);x_next(7)];
J = J + x_e'*Q*x_e + u_0'*R*u_0;