Why is the jacobian function so slow for calculating jacobian matrix with many variables?

2 visualizzazioni (ultimi 30 giorni)
I have 40 variables, define them in a symbolic vector and then use this vector to bulid a scalar cost-function. Now I want to use the jacobian function to calculate the jacobian matrix of this cost function. I think I will get the jacobian matrix with symbolics variables. But the computation is too slow. I guess maybe i've done something wrong somewhere.
In my code I set N_p to 20 and what i want to get the jacobian matrix of cost_fun about u.
The following is my main code:
x0 = sym('x0',[8 1],'real');
u = sym('u',[2*N_p 1],'real');
kappa = sym('kappa','real');
x = sym(zeros(8*N_p,1));
u0 = sym('u0',[2 1],'real');
f = cost_fun(x0,u,m,I_z,lf,lr,Cf,Cr,N_p,t,Q,x_ref,R1,R2,F_deltau,kappa,u0);
g=jacobian(f,u);
The following is my cost-function:
function f = cost_fun(x0,u,m,I_z,lf,lr,Cf,Cr,N_p,t,Q,x_ref,R1,R2,F_deltau,kappa,u0)
% cost function
x(1:8,1) = x0 + t * bicycle_model_2(x0,u(1:2,1),m,I_z,lf,lr,Cf,Cr,kappa);
for i=1:1:(N_p-1)
x((8*i+1):(8*i+8),1) = x((8*i-7):(8*i),1) + t * bicycle_model_2(x((8*i-7):(8*i),1),u((2*i+1):(2*i+2),1),m,I_z,lf,lr,Cf,Cr,kappa);
end
% u_0 = sym('u_0',[2*N_p 1],'real');
u_0(1:2,1)=u0;
u_0(3:2*N_p,1)=zeros(2*N_p-2,1);
f=(x-x_ref)'*Q*(x-x_ref)+u'*R1*u+(F_deltau*u-u_0)'*R2*(F_deltau*u-u_0);
end
function f=bicycle_model_2(x,u,m,I_z,lf,lr,Cf,Cr,kappa)
delta_f=u(1);F_xT=1000*u(2);
x_dot=x(1)+eps;y_dot=x(2);phi_dot=x(3);phi=x(4);X=x(5);Y=x(6);e_phi=x(7);e_y=x(8);
f1=(m*y_dot*phi_dot+F_xT)/m;
f2=(-m*x_dot*phi_dot+2*Cf*(delta_f-(y_dot+lf*phi_dot)/x_dot)+2*Cr*(-(y_dot-lr*phi_dot)/x_dot))/m;
f3=(lf*2*Cf*(delta_f-(y_dot+lf*phi_dot)/x_dot)-lr*(-(y_dot-lr*phi_dot)/x_dot))/I_z;
f4=phi_dot;
f5=x_dot*cos(phi)-y_dot*sin(phi);
f6=x_dot*sin(phi)+y_dot*cos(phi);
f7=phi_dot-kappa*x_dot;
f8=x_dot*sin(e_phi)+y_dot*cos(e_phi);
f=[f1 f2 f3 f4 f5 f6 f7 f8]';
In fact, I also want to change the result of jacobian matrix with symbolic variables into a function handle. But the matlabFunction costs much time, that can be unacceptable. Has someone some suggestions?
  2 Commenti
Torsten
Torsten il 27 Ago 2024
Modificato: Torsten il 27 Ago 2024
Don't use symbolic computation if speed is an issue. When the Jacobian is needed, use a finite-difference approximation for the derivatives.

Accedi per commentare.

Risposte (1)

Matt J
Matt J il 27 Ago 2024
Use matlabFunction to compute the jacobian from symbolic to numerical form, so that when it comes time to use it repeatedly, it will do so faster.

Prodotti


Release

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by