MATLAB Matlab for loop and difference equation question

AI Thread Summary
The discussion revolves around solving a difference equation using a for loop in MATLAB. The equation y(k+1) = -0.5*y(k) + x(k) is being implemented, but the user encounters an error due to attempting to access the 0th index of an array, which MATLAB does not support. The solution involves starting the loop at k=1 and initializing y(1) to 0 to correctly represent y(0). Additionally, a suggestion is made to track the previous value of y with a variable to maintain the correct time indexing. The user confirms that this adjustment resolves the issue.
Ethers0n
Messages
27
Reaction score
0
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.
 
Physics news on Phys.org
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.
 
Thanks.
That seemed to do the trick.

J
 
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
 

Similar threads

Replies
1
Views
2K
Replies
4
Views
1K
Replies
4
Views
2K
Replies
8
Views
2K
Replies
5
Views
2K
Replies
2
Views
3K
Replies
9
Views
3K
Replies
2
Views
3K
Back
Top