When designing a moving average filter in Simulink, it is normally not hard to create a model with basic Simulink blocks. However, in case of designing a moving average filter of 100 window size, it is not good idea to add 100 blocks of the Delay. So instead of using the Delay, we can use the block 'Matlab Function' where a moving average filter is coded.
* code
The picture code does not open for me
ReplyDeleteCan you write the code as a text please?
y = .... is missing
ReplyDeletefunction []=fcn(u)
Delete% moving average window
ws = 2 ;
%define variables
persistent n buf winSum;
% initialize
if isempty(buf)
buf = zeros(1,ws) ;
winSum=0 ;
n=1 ;
end
% Delete the oldest value saved in window
winSum = winSum - buf(n) ;
% add new value into window where oldest was deleted
buf(n) = u ;
winSum = winSum + u ;
% increase n
n = n + 1;
if n>numel(buf)
n = 1;
end
end
Here's a code i like more.
ReplyDeletefunction ymean = fcn( y )
persistent buf n buffull ;
ws = 5 ; % moving average window
% if isempty(buf)
% winSum = zeros(numel(y), 1) ;
% buf = zeros(numel(y), ws) ;
% n = 1 ;
% end
%
% winSum = winSum - buf(:, n) ; % delete oldest value
% winSum = winSum + y ; % add new value
% ymean = winSum ./ min(n, ws) ; % if n ws
% n = 1;
% end
if isempty(n)
n = 1 ;
buf = zeros(numel(y), ws) ;
buffull = 0 ;
end
buf(:, n) = y ;
ymean = y ;
if buffull % averaging only starts after buffer full
ymean = mean(buf, 2) ;
end
n = n + 1;
if n > ws
n = 1 ;
buffull = 1 ;
end
end