How to code a moving average in a matlab function block using persistent variables
24 views (last 30 days)
Show older comments
Hi all,
I'm trying to code a moving average in a MATLAB function block (I don't have access to the DSP toolbox). The block needs to take 1 input signal and then release a single output. However, the block is within a subsystem that is part of a closed loop system that will receive both new inputs, as well as 'recycled' inputs.
I've tried to declare a persistent variable that stores the inputs and then calculates a moving average to output a single signal every time a new 'slug' of material passes through the subsystem - BUT I'm not getting anywhere fast (I'm new to MATLAB/Simulink) and would greatly appreciate someone's help!
I've tried something along the lines of:
function Aprime = fcn(A)
persistent A_array
if isempty(A_array)
A_array = zeros([],1); % this trying to create an empty array to append/concatenate each new value of A \
% that passes through the block
end
A_array = [A_array, A];
Aprime = movmean(A_array, 3) % the '3' is arbitrary at this point.
end
This block of code clearly does not function, and I'm getting errors with persistent variable assignment orders, left side array does not equal right side, etc., etc. depending on what combination of things I try.
While I've tried to use the 'movmean' built-in function here just to get me started, it doesn't really capture what I need either, as I need just one mean as an output signal each time a slug of material flows through the block.
I think maybe something along the lines of declaring an persistent index ('idx') variable and 'sliding' the window by a tunable size (user-defined) would be best, but I'm really not sure how to go about this.
Anybody's help would be UBER appreciated!
Thanks in advance.
Cheers
6 Comments
Rik
on 26 May 2022
Feel free to explain what you did in an answer. That way, future readers will be able to use your solution.
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Logical 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!