# How to define y[n] = f1 y[n-1] + u[n]?

I need to define a recursion defined by the following equation

$y(n) = f_1 y(n-1) + u(n)$

In which $f_1$ is a symbolic constant. I know the values of the sequence u and I know the initial value of y.

Now if I tried to type this in Mathematica (see below) I get an error because I don't have a lower limit for my index. How do I make Mathematica understand that Im starting my sequences from 0?

yhat[n_] := -f1 yhat[n - 1] - f2 yhat[n - 2] + u[n]
yhat[0] = 0;
yhat[5]


During evaluation of In[3]:= $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> > During evaluation of In[3]:=$RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> During evaluation of In[3]:= $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> >During evaluation of In[3]:=$RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> During evaluation of In[3]:= General::stop: Further output of $RecursionLimit::reclim will be suppressed during this calculation. >> Out[3]  ## 1 Answer With your definition, you have yhat[1]  u[1] - f2 yhat[-1] - f1 yhat[0] But you haven't defined yhat for negative numbers! The function then jumps the termination clause and would go to -Infinityif it weren't for $RecursionLimit.

You can fix it by applying the recursion clause only to positive numbers

Clear[yhat];
yhat[n_?Positive] := -f1 yhat[n - 1] - f2 yhat[n - 2] + u[n]
yhat[_] := 0;
yhat[5]


-f2 (-f2 u[1] - f1 (-f1 u[1] + u[2]) + u[3]) - f1 (-f2 (-f1 u[1] + u[2]) - f1 (-f2 u[1] - f1 (-f1 u[1] + u[2]) + u[3]) + u[4]) + u[5]

You could also apply the termination clause only to NonPositive numbers

Clear[yhat];
yhat[n_?NonPositive] := 0;
yhat[n_] := -f1 yhat[n - 1] - f2 yhat[n - 2] + u[n]


Somewhat important: Notice that the order of the clauses have changed. The termination clause is now before the recursive one. You should always define functions from the more specific to the more general case.

• What is the role of yhat[_] := 0; ? Can I set my initial values: y[-1] and y[-2] ? Nov 19, 2014 at 16:55
• _ matches anything. So it will match everything that the other patterns haven't caught. Yes, you can assign more values, but always put specific definitions before general ones, otherwise the general will "steal" matches! Nov 19, 2014 at 17:00