Implementing Euler's method for a 1D system

1 view (last 30 days)
I'm having trouble implementing euler's method for 𝑓(𝑥) = 𝑥^3 + 𝑥^2 − 12𝑥. I originally plotted the function just fine using this script:
x = [-5:0.1:5];
y = x.^3 + x.^2 - 12*x;
plot(x,y)
grid on.
Then when I try to implement euler's method to this function, I'm not receiving the same graph and am confused why. If I change anything in the x constraint it says my arrays are incorrect. If I change N for my number of steps it says incorrect arrays. And anything I put into my initial condition y(1) alters where the graph ultimately lays but never correctly on the roots.
h=0.1;
x=-5:h:5;
N=100;
y=zeros(size(x));
y(1)=0;
n=numel(y);
for n=1:N
dydx=3*x(n).^2+2*x(n)-12;
y(n+1)=y(n)+dydx*h;
end
plot(x,y);
grid on;
I did follow the basic steps for implementing euler's method that I am aware of, but it's not creating the graph I expect.
Ultimately I was supposed to plot the original function, then implement the 1D system using euler's method and x(t). But I can't get the code to run correctly for just the 1D system alone, let alone x(t).

Accepted Answer

KSSV
KSSV on 3 Oct 2022
h=0.1;
x=-5:h:5;
y=zeros(size(x));
y(1)=0;
for n=1:length(x)-1
dydx=3*x(n).^2+2*x(n)-12;
y(n+1)=y(n)+dydx*h;
end
plot(x,y);
grid on;
  5 Comments
Kristina
Kristina on 3 Oct 2022
I see so it's because I'm implementing Euler's method and the possible mistakes on it it's just never going to sit on the roots as just plotting the function. This makes sense thank you so much!
Torsten
Torsten on 3 Oct 2022
Well, I don't understand what you mean, but you're welcome ! :-)

Sign in to comment.

More Answers (0)

Categories

Find more on Numerical Integration and Differential Equations in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!