efficiency of code: function call with structure vs script
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Austin Coffman
am 28 Mär. 2018
Beantwortet: Walter Roberson
am 28 Mär. 2018
Hello, I have implemented a piece of code two ways and the times of computation are drastically different. I am currently not able to understand why. Here are the two methods: Method 1:
for k=2:1:N
U = uKal(:,k-1);
Y_k = Y(:,k);
P_k_m = sysEST.A*P_k_p*Atrans + Q_k;
K_k = P_k_m*Ctrans/(sysEST.C*P_k_m*Ctrans+R_k);
x_hat_m = sysEST.A*x_hat_p + sysEST.B*U;
% r(k) = Y_k - sysEST.C*x_hat_m;
x_hat_p = x_hat_m + K_k*(Y_k - sysEST.C*x_hat_m);
P_k_p = (I - K_k*C)*P_k_m;
xHatHist(:,k) = x_hat_p;
end
Method 2:
for k=2:1:N
%extract measurements:
s.U = uKal(:,k-1);
s.Y_k = Y(:,k);
%advance kalman filter:
s = kalmanfilt(s);
%save the state:
xHatHistTwo(:,k) = s.x;
end
Here is the kalmanfilt function:
function s = kalmanfilt(s)
%a prior estimates:
P_k_m = s.A*s.P*s.Atrans + s.Q;
x_hat_m = s.A*s.x + s.B*s.U;
%compute kalman gain:
K_k = P_k_m*s.Ctrans/(s.C*P_k_m*s.Ctrans + s.R);
% r(k) = Y_k - sysEST.C*x_hat_m;
%a posteriori estimates:
xHat = x_hat_m + K_k*(s.Y_k - s.C*x_hat_m);
P_k_p = (s.I - K_k*s.C)*P_k_m;
%output structure:
s.x = xHat;
s.P = P_k_p;
end
The computation time for method 1 is 2 seconds and the computation time for method 2 is 0.01 seconds. Does anyone have an explanation of this. Also, any comments on how to further improve the efficiency are welcome too. Thank you.
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 28 Mär. 2018
scripts are less Just In Time compiled than functions are, but how much less has been changing over the releases, with more and more JIT being done for scripts (which is affecting the interpretation of scripts that "poof" variables into existence.)
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu State-Space Control Design and Estimation finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!