%% Using CasADi for differentiation % Download at https://web.casadi.org/ %% Scalar case import casadi.* % Create a symbolic scalar variable x = MX.sym('x',1); % Use the symbolic variable to define the cost function y = cos(x^2) % Compute the derivative of the cost function grad_y = gradient(y,x) % Build a function object f = Function('f',{x},{grad_y}); % Evaluate the function at a given numerical value of the variable xnum = 2 grad_y_num = f(xnum) %% Vector case % Create a symbolic vector x = MX.sym('x',2); % Use the symbolic vector to define the cost function Q = [2 1; 1 4]; y = 1/2*x'*Q*x % Compute the gradient of the cost function grad_y = gradient(y,x) % Build a function object f = Function('f',{x},{grad_y}); % Evaluate the function at a given numerical value of the vector xnum = [1;3] grad_y_num = f(xnum)