Execute Matlab function in Simulink
Show older comments
Hello to all,
I have this Matlab function, i would like to execute in Simulink using "User-Defined->Matlab Function" from the Library.
This is the function I want to execute:
function y = moving_average2(u, Tf, Ts)
% Check if the input data is long enough
N = ceil(Tf/Ts);
if numel(u) < N
N = numel(u);
end
% Initialize the result array
y = zeros(size(u));
disp(N)
% Calculate the moving average
for i = N:numel(u)
y(i) = mean(u(i-N+1:i));
end
end
and when tested, I have called this function from the following simple script:
clear; clc; close all
t = 0:0.1:10;
u = sin(t);
Tf = 2; T = 0.1;
y = moving_average(u, Tf, T);
plot(t, u);hold on; grid on;
plot(t, y, 'r');
legend("Input", "Output");
The above script when executed produce the following result:

However, when this very same function is called from the Simulink as shown in picture:

The result is very different, as if averaging is not applied at all. Input and output signals are matching perfectly (Simulation s 10 sec, auto, fixed size (auto).
Can you please suggest what I'm doing wrong?
My guess it is because Simulink executes this function for each input sample, and that is the difference comparing with the script, so basically I would need to modife the function as it would be called in an infinite loop in cyclic manner.
Thank you!
Accepted Answer
More Answers (0)
Categories
Find more on Collect Coverage for Models 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!
