Execute Matlab function in Simulink
显示 更早的评论
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!
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Collect Coverage for Models 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

