How to create a buffer and mean function for a real time/timeseries data

5 visualizzazioni (ultimi 30 giorni)
I am trying to make a moving average function for using in Simulink model. Intially, I used the Simulink blocks "moving average" and "buffer and mean", but the microcontroller I am using is not accepting the c-code generated for these blocks.
So, I am trying to write an user defined function that creates a fixed sample buffer, and changes at each time step (taking the new value and deleting the oldest value), calculates a mean for that buffer in each time step. The data I am using is timeseries, finally it will be real time data, So I dont have the full data when analysing, the buffer needs to be developed one sample at a time.. and the inital values will be 0.
So far, I have written the code as below.. I have also shared a snapshot of the model and error
The error I am getting is that variables are "variable size".
Can you please suggest, where the logic in my code is wrong?
Also, is there any better way to make the averaging, without using the above mentioned simulink blocks.
Have a nice day.
function [mean_val,new_buffer] = fcn(u,old_buffer)
buffer_size = 100 ;
if isempty(old_buffer)
old_buffer = double(zeros((buffer_size-1),1));
end
%%% input
current_val = double(u);
old_val = double(old_buffer);
% initialize
persistent sig_buffered
persistent sig_mean
if isempty(sig_buffered)
sig_buffered = double(zeros(buffer_size,1));
sig_mean = double(zeros(1,1));
end
%% setting values
sig_buffered(1,1) = current_val;
sig_buffered(2:buffer_size,1)= old_val;
sig_mean = mean(sig_buffered(1));
%% output
mean_val = double(sig_mean);
new_buffer = sig_buffered((1:(end-1)),1);
end

Risposte (1)

Yash
Yash il 6 Set 2023
Modificato: Yash il 8 Set 2023
Hi Ritam,
I understand that you are interested in calculating the moving average of incoming data using a custom MATLAB function in Simulink.
After reviewing your code, I have identified a correction that needs to be made. Modify the line where you are setting "sig_mean" as follows:
sig_mean = mean(sig_buffered);
I have replicated the same model at my end using MATLAB R2022b, and it successfully produced the desired results.
To verify the correctness of the implementation, I used the following value for "T_in" (with a maximum step size of 0.05):
T_in = timeseries(100*ones(201,1),0:0.05:10)
This sets "T_in" as a constant value of 100, resulting in the output rising from 0 to 100 and then staying constant at 100. Have a look below at the output I obtained for your reference.
If you are facing issues related to loading timeseries data, kindly refer to this article: link.
I hope this helps you address the issue.

Categorie

Scopri di più su Simulink in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by