Forward Euler method error
14 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I am trying to create a loop to solve a system of differential equations, where x' = -y and y' = x. The initial conditions given are x(0) = r and y(0) = 0, but r can be set as any arbitrary number and it won't change the solution too much. I am getting this error that says "Array indices must be positive integers or logical values", but I am confused because I am nonly trying to set initial conditions. ANY help is greatly appreciated!!!

0 Commenti
Risposta accettata
Torsten
il 28 Apr 2022
Modificato: Torsten
il 28 Apr 2022
Array indices in MATLAB start at 1, not at 0.
Thus you will have to replace
x(0)=1
y(0)=0
by
x(1)=1
y(1)=0
And you solve the wrong equations. What you solve is
x' = -t
y' = y
Look at how you call dxdt and dydt.
In both cases, the call must be
x(n+1) = x(n) + h*dxdt(x(n),y(n))
y(n+1) = y(n) + h*dydt(x(n),y(n))
Further, by the line
t(n+1) = a+n*h
you overwrite the t-vector you've already created by
t=a:h:b
So you should delete this line.
4 Commenti
Torsten
il 3 Mag 2022
Modificato: Torsten
il 3 Mag 2022
As I wrote in my first response, the call to dydt must be
x(n+1) = x(n) + h*dxdt(x(n),y(n))
y(n+1) = y(n) + h*dydt(x(n),y(n))
instead of
x(n+1) = x(n) + h*dxdt(x(n),t(n))
y(n+1) = y(n) + h*dydt(y(n),t(n))
as you first did, and that's what you finally found out by yourself. That's optimal.
Più risposte (1)
KSSV
il 28 Apr 2022
The loop should be taken as:
for i = 1:round(N)
In your present case, it is a fraction and you are getting non integers as the indices and error is pooped.
% Demo
N = 10.2;
for i = 1:N
i
A(i) = rand ; % error, index cannot be fraction
end
0 Commenti
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



