Search code examples
functionmatlabargumentsiterationpersistent

Pass a Previous Value to function MATLAB


I have the following function:

y(t) = alpha*y(t-1) + beta*y(t-1) + delta

where alpha,beta, and delta are constants.

I am assuming that y(0) = 0. I'm trying to create a MATLAB function to represent y(t) using the persistent command. I pass 0 as the initial condition for y(t) when I call my function for the first time. I then use a for loop to update y(t) for 1000 iterations. For some reason my output for y(t), y_out, never changes in size and remains 0. I'm not sure why this is happening. How do I get y(t) to update iteratively as t increases?

alpha = 0.5;
beta = 0.3;
delta = 0.8;

y_out = NARMA(alpha,beta,delta,0);

for t=2:1:1000
    y_out = NARMA(alpha,beta,delta); 
end

function y_out = NARMA(alpha,beta,delta,varargin) % pass 0 to varargin as y(0) = 0 only the first time you call the function
 persistent y
 if nargin>3
     y = y + alpha*varargin{1} + beta*varargin{1} + delta
 end
 y_out = y;
end

Solution

  • I think you're complicating your program with the persistent variable. I would implement it this way:

    alpha = 0.5;
    beta = 0.3;
    delta = 0.8;
    
    N = 100;
    y_out = zeros(1, N);
    y_out(1) = NARMA(0,alpha,beta,delta);
    for t=2:N
        y_out(t) = NARMA(y_out(t-1),alpha,beta,delta);
    end
    
    function y_out = NARMA(y_in,alpha,beta,delta)
        y_out = alpha*y_in + beta*y_in + delta;
    end
    

    Because the function is now one line, you could instead use an anonymous function like so:

    alpha = 0.5;
    beta = 0.3;
    delta = 0.8;
    
    NARMA = @(y_in) alpha*y_in + beta*y_in + delta;
    
    N = 100;
    y_out = zeros(1, N);
    y_out(1) = NARMA(0);
    for t=2:N
        y_out(t) = NARMA(y_out(t-1));
    end
    

    Note how the anonymous function (also called a lambda) captures the value of the variables alpha, beta and delta at the moment it's defined. We don't need to pass these in as function arguments, they've become part of the function.


    If you insist on using a persistent variable, you could do it this way:

    alpha = 0.5;
    beta = 0.3;
    delta = 0.8;
    
    N = 100;
    y_out = zeros(1, N);
    y_out(1) = NARMA(alpha,beta,delta,true);
    for t=2:N
        y_out(t) = NARMA(alpha,beta,delta);
    end
    
    function y_out = NARMA(alpha,beta,delta,first_call)
        % Set first_call to true only the first time you call the function
        persistent y
        if nargin>3 && first_call
            y = 0;
        end
        y = alpha*y + beta*y + delta;
        y_out = y;
    end