# Matlab for loop and difference equation question

1. Mar 30, 2005

### Ethers0n

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)

end

Thanks for any help.

2. Mar 31, 2005

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);
end

Then the time index will be correct, but your y values won't tell you that y(0) = 0.

3. Mar 31, 2005

### Ethers0n

Thanks.
That seemed to do the trick.

J

4. Sep 15, 2009

### ananthan

how to solve the following difference equation in matlab
y(n)=0.5y(n-1)+0.2y(n-2)+.78y(n-3)+x(n)+.2x(n-1)
my input is unit step