How to use MATLAB to solve difference equations with initial conditions

조회 수: 8 (최근 30일)
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

채택된 답변

Khalid
Khalid 2023년 1월 19일
편집: Khalid 2023년 1월 19일
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
Johnathan Yeung
Johnathan Yeung 2023년 1월 19일
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!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by