Implementing a Discrete Integrator in a Function

10 次查看(过去 30 天)
I am currently using a discrete integrator block in Simulink. It is part of a PLL, so I need it to integrate up to 2*pi then reset to zero and repeat, exactly as it does in the included Simulink 3-ph PLL block.
I would now like to implement this integrator as a MATLAB function as a prelude to implementing it in C code. However, I have run into a problem as I need to use persistent variables to store the state, however, Simulink does not allow persistent variables within an algebraic loop. Instead of using persistent variables, I tried to use variables stored in the MATLAB workspace and pass them as parameters, however, MATLAB passes them by value so the original variables remain unaltered after each iteration.
Has anyone tackled this issue before?

回答(1 个)

Euan Andrew
Euan Andrew 2020-9-7
I have since found a workaround for my own problem, so I'm posting it here for the benefit of others. I gave up on trying to use a Trapezoidal integration approach and reverted to the Forward Euler method since it has no direct feedthrough of the input. The code is shown below:
function y_k = fcn(u_k, Ts)
persistent x_k1 initial_condition step_zero
if isempty(x_k1), x_k1 = 0; end
if isempty(initial_condition), initial_condition = 0; end
if isempty(step_zero), step_zero = 1; end
K = 1;
x_k = x_k1;
if(step_zero == 1)
y_k = initial_condition;
x_k1 = y_k + K*Ts*u_k;
step_zero = 0;
else
y_k = x_k;
x_k1 = x_k + K*Ts*u_k;
end
if(x_k1 > 2*pi)
initial_condition = x_k1 - 2*pi;
step_zero = 1;
end
This code is equivalent in function to the pictured Simulink blocks.
Finally, double click the function block to open the Function Editor, in the Simulink Pane at the top, select Edit Data, then uncheck Allow Direct Feedthrough.

类别

Help CenterFile Exchange 中查找有关 General Applications 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by