Euler's Method with multiple step sizes

조회 수: 11 (최근 30일)
Max
Max 2023년 4월 6일
댓글: Max 2023년 4월 6일
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

채택된 답변

Torsten
Torsten 2023년 4월 6일
%%% 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
  댓글 수: 1
Max
Max 2023년 4월 6일
Thank you so much, you're a life saver

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by