How to use MATLAB to solve difference equations with initial conditions

53 views (last 30 days)
To begin this I would like to state that I have only recently started using MATLAB since one of my classes requires it. For one of my assignments I have to use loops in MATLAB to solve a difference equation.
The equation has an input x(n) and initial conditions, with one condition starting at 0, and the other starting at -1.
I won't post the exact question itself, as I would like to make the code myself after understanding how to do it.
An example of the problem is as follows:
,
The a,b,and c in the above example can be any value, but since I'm attempting to make a code, I've set the values to each be
This is my attempt at the code (it does not work and gets an error at "y(0) = 1"):
%---Example for Mathworks Community QnA Forum---
% arbitrary constants
a = 0.5;
b = 0.5;
c = 0.5;
%initial conditions
y(0) = 1;
y(-1) = -1;
% loop for finding y(n)
for n = 1:10
x(n) = c^n;
y(n) = x(n-1) -a*y(n-1) - b*y(n-2)
end

Accepted Answer

Khalid
Khalid on 19 Jan 2023
Edited: Khalid on 19 Jan 2023
Hello,
It is my understanding that you are facing an error at line "y(0)=1" in the above program.
You are facing this error because in that line, "y" is interpreted as an array and "y(0)" is trying to access the 0th index of the array "y". In MATLAB, array indexing is 1-based i.e array starts with index 1. So, any integer less than 1 is not a valid index.
For the example problem, you need the initial value of "x" i.e "x(0)" to solve the problem. Assuming, we have "x(0)", one possible way to solve the example problem could be as follows:
a = 0.5;
b = 0.5;
c = 0.5;
%initial conditions
y0 = 1;
yminusone = -1;
%change next line with the value of x(0)
x0 = 10
% loop for finding y(n)
for n = 1:10
x(n) = c^n;
if n == 1
y(1) = x0 -a*y0 - b*yminusone;
elseif n == 2
y(2) = x(1) - a*y(1) - b*y0;
else
y(n) = x(n-1) - a*y(n-1) - b* y(n-2);
end
end
  1 Comment
Johnathan Yeung
Johnathan Yeung on 19 Jan 2023
Oh okay so to solve a difference equation with a loop I have to first solve for the situations that involve the initial conditions (using an if - else if - else structure). Then I can have the code solve through the remaining iterations since the initial situations are solved for.
Thanks a bunch! This helped greatly!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!