Euler Method IVP Coding Help
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have an IVP problem I'm trying to solve with Euler's Method. The problem is: dy/dx = 1-x+1, y(0) = 1. My time step is 0.01 and my x final is 3. I get an "Index exceeds matrix dimensions." error when I try and run the code. Where am I going wrong? Here is my code:
clear; clc;
%inputs
xo=input('Enter x initial: ');
yo=input('Enter y initial: ');
dx=input('Enter delta x (time step): ');
xf=input('Enter x final: ');
x(1)=xo;
y(1)=yo;
n=1;
% function [out] = Euler(x,y)
% out=1-x+y;
% end
while x(n)<=xf
y(n+1)=y(n)+Euler(x(n),y(n))*(dx);
n=n+1;
end
0 Kommentare
Antworten (2)
Aquatris
am 30 Jul. 2018
Your x vector only has a single element in it. After while loop goes once, it tries to reach x(2), which does not exist. That is why you are getting index exceeds error.
0 Kommentare
John
am 5 Aug. 2023
w0=0.5;
a=0;
b=2;
hh=[0.5 0.2 0.1 0.05 0.01 0.005 0.001];
f=@(t,y) y-t^2+1;
for j=1:7
we(1,j)=w0;
wm(1,j)=w0;
wr(1,j)=w0;
h=hh(j);
n=(b-a)/h;
for i=1:n
t=(i-1)*h;
we(i+1,j)=we(i,j)+h*f(t,we(i,j));
wm(i+1,j)=wm(i,j)+h*f(t+h/2,wm(i,j)+(h/2)*f(t,wm(i,j)));
k1=h*f(t,wr(i,j));
k2=h*f(t+h/2,wr(i,j)+k1/2);
k3=h*f(t+h/2,wr(i,j)+k2/2);
k4=h*f(t+h,wr(i,j)+k3);
wr(i+1,j)=wr(i,j)+(1/6)*(k1+2*k2+2*k3+k4);
end
error_we(j)=abs(we(n+1,j)-y(2));
error_wm(j)=abs(wm(n+1,j)-y(2));
error_wr(j)=abs(wr(n+1,j)-y(2));
end
% y=@(t)....
t=a:h(3):b;
plot(t,y(t),)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!