efficiency of code: function call with structure vs script
Show older comments
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.
Accepted Answer
More Answers (0)
Categories
Find more on State-Space Control Design and Estimation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!