How can I get a sum of elements over a specified sample period in simulink?

4 views (last 30 days)
Hello all,
Trying to create a simple block average using simulink model based coding but I am having trouble. My code runs on 1ms sample times and I'd like to get a block average of 32 inputs. The logic in my head is easy... sum up 32 inputs and divide by 32. Now I tried using the sum of elements block but had no success. How I can get a sum every 32 inputs?

Answers (1)

Andy Bartlett
Andy Bartlett on 11 May 2022
For the case you described, a known fixed sample time (1ms in your case) and a know fixed time window (32ms in your case) to average over, the simplest way to model this would be to drop in an FIR.
Set the FIR coefficient to
tSamp = 0.1;
tWindow = 0.32;
nNumCoef = round( tWindow / tSamp );
firNumeratorCoef = ones(1,nNumCoef)./nNumCoef;
An FIR is a weighted sum ot the last numel(firNumeratorCoef) inputs which is exactly what you are looking for.
The FIR will do N multiplications and N-1 additions. Your problem could be handled with just N-1 additions followed by 1 multiplication (or 1 division).
If you want to increase efficiency (fewer multiplications), you could look at using a Tapped Delay block or a Buffer Block combined with a reducing Sum block followed by a Gain Block with value (1/32).
The FIR and Tapped Delay approaches will output an average every 1ms, so it's "streaming".
The Buffer block approach will output an average every 32ms, so it's "batching."
If your requirements are more specific you can roll up your sleeves and craft just about anything you want by wiring together the logic using triggerable-resetable delays, etc.




Community Treasure Hunt

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

Start Hunting!