1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Difference equation

  1. Sep 3, 2006 #1
    plz help me to implement this difference equation in MATLAB????


    matlab is not supportin -ve index....
  2. jcsd
  3. Sep 3, 2006 #2
    Matlab doesn't like negative indexes as you seem to have noticed. But there are at least three easy ways to get around this.
    Code (Text):

    n = [0:100]; N = length(n);
    x = cos(n/25);

    % option 1
    y1(1) = x(1) - cos(-1/25); %compute y(1) first
    for i = 2:N
        y1(i) = x(i)-x(i-1);

    % option 2
    x0 = cos(-1/25); %define x(-1) outside loop
    for i = 1:N
        y2(i) = x(i) - x0;
        x0 = x(i);

    % option 3
    n2 = [-1:99]; % use vectors instead of loop
    xn = cos(n/25);
    xn_minus_one = cos(n2/25);
    y3 = xn-xn_minus_one;
    If you want to use a loop, you can loop over i=2:N and define y(1) outside of the loop.

    Another option is to loop from i=1:N and define x(n-1) as x0 and update it at each step, that way you never try to acces x(-1).

    If you don't want to use a loop, you can just create vectors for x[n] and x[n-1] over a big range of n, and just compute y by subtracting those long vectors.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook