How to create a buffer and mean function for a real time/timeseries data
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponses (1)
Yash
le 6 Sep 2023
Modifié(e) : Yash
le 8 Sep 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.
I hope this helps you address the issue.
0 commentaires
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!