Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Matlab for loop and difference equation question

  1. Mar 30, 2005 #1
    I'm attempting to solve a difference equation

    y(k+1) = -0.5*y(k) + x(k)

    where y(0) = 0 and x(k) is in my case a unit step function ie = 1

    well, i'm trying to solve this using a for loop, but am having some trouble. The code i've generated gets an error, "Index into matrix is negative or zero."

    Any ideas?
    My code is below.

    k = 0 ; %counter variable
    y = 0; %y(k)
    x = 1; %x(k), unit step function

    for k = 0 : 5

    y(k+1) = -.5*y(k) + x;

    y(k) = y(k+1)


    Thanks for any help.
  2. jcsd
  3. Mar 31, 2005 #2
    Matlab doesn't like to store things in the 0th element of an array. Your loop starts at k=0, so it's trying to access y(0) which doesn't exist. You'll have to start at k=1 and just know that k=1 corresponds to t=0.

    Also, it doesn't look like you have actually told it that y(0) = 0. You need to say y(1) = 0.

    If you really want y(1) to be time = 1, you could do something like

    yold = 0;

    for k = 1:5
    y(k) = -0.5*yold + x;
    yold = y(k);

    Then the time index will be correct, but your y values won't tell you that y(0) = 0.
  4. Mar 31, 2005 #3
    That seemed to do the trick.

  5. Sep 15, 2009 #4
    how to solve the following difference equation in matlab
    my input is unit step
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?

Similar Discussions: Matlab for loop and difference equation question
  1. For loop in matlab (Replies: 3)