Euler's Method with multiple step sizes

12 visualizzazioni (ultimi 30 giorni)
Max
Max il 6 Apr 2023
Commentato: Max il 6 Apr 2023
I am currently working on a project for my differential equations class and this is the first part. Most of this was written by my professor, and I cannot find the problem with this code. When I try to run it, I recieve the error shown at the end. Can anyone help me fix this problem?
%%% Define the interval [a,b] and initial condition
a = 0;
b = 0.5;
y0 = 1;
%%% Find the approximated solution using Euler's method
N = 10; %%% number of steps
[x1,y1] = Euler(a,b,y0,N); %%% use the function "Euler" to find the approximate solution with step size h=0.05
N = 100; %%% number of steps
[x2,y2] = Euler(a,b,y0,N); %%% use the function "Euler" to find the approximate solution with step size h=0.005
%%% Define the exact solution
N = 100;
x3 = a:(b-a)/N:b;
y3 = @(x) 2*exp.(x) - x - 1;
%%% Plot the 3 solutions on the same figure
figure;
plot(x1,y1,'r'); hold on;
plot(x2,y2,'g'); hold on;
plot(x3,y3,'b'); hold off;
%%% Euler's method
function [x,y] = Euler(a,b,y0,N)
h = (b-a)/N;
x = a:h:b;
y = zeros(size(x));
f = x+y;
x(1) = a;
y(1) = y0;
%%% main loop for Euler's method
for i = 1:N-1
y(i+1) =y(i) + h * f;
end
end
Unable to perform assignment because the left and right sides have a different number of elements.
Error in Project2_Q1>Euler (line 48)
y(i+1) =y(i) + h * f;
Error in Project2_Q1 (line 16)
[x1,y1] = Euler(a,b,y0,N); %%% use the function "Euler" to find the approximate solution with step size h=0.05

Risposta accettata

Torsten
Torsten il 6 Apr 2023
%%% Define the interval [a,b] and initial condition
a = 0;
b = 0.5;
y0 = 1;
%%% Find the approximated solution using Euler's method
N = 10; %%% number of steps
[x1,y1] = Euler(a,b,y0,N); %%% use the function "Euler" to find the approximate solution with step size h=0.05
N = 100; %%% number of steps
[x2,y2] = Euler(a,b,y0,N); %%% use the function "Euler" to find the approximate solution with step size h=0.005
%%% Define the exact solution
N = 100;
x3 = a:(b-a)/N:b;
y3 = 2*exp(x3) - x3 - 1;
%%% Plot the 3 solutions on the same figure
figure;
plot(x1,y1,'r'); hold on;
plot(x2,y2,'g'); hold on;
plot(x3,y3,'b'); hold off;
%%% Euler's method
function [x,y] = Euler(a,b,y0,N)
h = (b-a)/N;
x = a:h:b;
y = zeros(size(x));
f = @(x,y)x+y;
y(1) = y0;
%%% main loop for Euler's method
for i = 1:N
y(i+1) =y(i) + h * f(x(i),y(i));
end
end

Più risposte (0)

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by