efficiency of code: function call with structure vs script

2 ビュー (過去 30 日間)
Austin Coffman
Austin Coffman 2018 年 3 月 28 日
回答済み: Walter Roberson 2018 年 3 月 28 日
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.

採用された回答

Walter Roberson
Walter Roberson 2018 年 3 月 28 日
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 件)

カテゴリ

Help Center および File ExchangeState-Space Control Design and Estimation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by