How to use MATLAB to solve difference equations with initial conditions
41 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Johnathan Yeung
le 19 Jan 2023
Commenté : Johnathan Yeung
le 19 Jan 2023
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
0 commentaires
Réponse acceptée
Khalid
le 19 Jan 2023
Modifié(e) : Khalid
le 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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!