Simple lowpass filter code for matlab, suitable to remove high frequency noise from measures.
This code filters 3 columns of data (plus an index in first column) and displays a plot with the original and filtered data. After that, it does it again using a different lowpass equation, just for comparision.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | function y = lowpass(x,dt,RC) % y=lowpass(data,dt,RC); % data (x) rows: [ sample_num, X_value, Y_value, Z_value] % output (y) rows: [X_value, Y_value, Z_value, X_filtered, Y_filtered, Z_filtered] alfa= dt / (RC + dt) num=length(x) cols=4; for j=1:cols y(1,j)=x(1,j); end for i=2:num for j=2:cols y(i,1)=x(i,1); y(i,j) = alfa * x(i,j) + (1-alfa) * y(i-1,j) ; end end figure hold on y=cat(2,x(:,2:4),y(:,2:4)) plot(x(:,1)*dt,y) title(['low1 RC=',num2str(RC)]) legend('X','Y','Z','Xf','Yf','Zf') % Alternative lowpass a = exp(-dt / RC); b = 1.0 - RC * (1.0 - a) / dt; c = 1.0 - b - a; for i=2:num for j=2:cols y(i,1)=x(i,1); y(i,j) = a * y(i-1,j) + b * x(i,j) + c * x(i-1,j); end end y2=cat(2,x(:,2:4),y(:,2:4)) plot(x(:,1)*dt,y2) title(['low2 RC=',num2str(RC)]) legend('X','Y','Z','Xf','Yf','Zf') |



