Search code examples
matlabfeedback-loop

How to implement a feedback loop in Matlab?


Consider a block scheme where there is a feedback path and the feedback signal is filtered by some kind of filter.

How can I implement this in Matlab (not Simulink)? My doubt is particularly about the filter: what interval of the signal should I choose to perform the filter?

For example if the filter has n coefficients, is it enough to filter the interval of the signal from i_n to i where i is the current iteration step?

I would like to replicate the behaviour of Simulink for the feedback loop but I found there is no way to export a simulink model to a Matlab script.


Solution

  • To your first question, the interval is depending on your sampling time. However, to implement the actual simulink behavior, that also depends on your solver options. Of course, it would be easy to implement an fixed-step solver than variable step one.

    Now let's consider a simplest feedback amplifier as

    In--->----Add--->----Gain--->---Out
               |           |
               ^           V
               |--filter---|
    

    If filter has n coefficients, you will need memory to retain the previous input (assume an FIR filter). This is where persistent variable comes in handy. So your call may look like:

    %% Sample Pseudocode. Do not run it until you fully understand.
    
    function xo = feedbackTest(xi)
    n = numel(xi);
    xo = zeros(n,1);
    for idx = 1:n // feed through and feedback
        xo(idx) = fsystem(xi(idx)) + xi(idx); 
    end
    %% ---------- filter ---------
    function out = fsystem(in)
    % y = a1[n] + a2[n-1] + a3[n-2]; // you need to insert your coefficients 
    persistent x1 x2 x3; // retain previous inputs
    if isempty(x2) x2 = 0; end
    if isempty(x1) x1 = 0; end
    x3 = x2;
    x2 = x1;
    x1 = in;
    out = a1*x1 - a2*x2 + a3*x3;
    

    And of course, the above example is just a demo for showing it's possible to design feedback loop using script/function. For a very complex system, it's still possible to implement but will be very difficult to put without using Simulink. You would very likely spend most of the time designing your filter modules instead of doing actual control mechanism.

    [Edit]

    For IIR filter such as Butterworth, that will involve feedforward path in your filters/system. However, the implementation concept is similar as shown in fsystem(). It will be better to write a function that generate appropriate coefficients in according to your cutoffs and ripples (assume you know the equations), and then apply your filter in the system. That you don't have to hard-coding coefficients every time when you need a new filter in your entire model.

    Hopefully, that answers your question.