Implementing Euler's method for a 1D system

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).

 Réponse acceptée

KSSV
KSSV le 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 commentaires

Kristina
Kristina le 3 Oct 2022
Shouldn't the graph when plotted have the zeros at the correct places? I might be mistaken and just misunderstanding what this graph is showing me, but I assumed when I implemented euler's method it should show me the same graph as just plotting the original function, but this one gives me a 0 at -5 and the zeros are -4,0, and 3 but it doesn't ever hit it with this code or my original code.
KSSV
KSSV le 3 Oct 2022
How and why they would be same? The purpose of Euler method is solving an ODE. You don't have any differential equation here.
If you want to reproduce the given function f, you must apply Euler's method on the function's derivative f' with initial value at x=-5 given as f(-5):
y = @(x) x.^3+x.^2-12*x;
dy = @(x) 3*x.^2+2*x-12;
h = 0.1;
x = -5:h:5;
ynum = zeros(size(x));
ynum(1) = y(x(1));
for n = 1:length(x)-1
ynum(n+1) = ynum(n) + dy(x(n))*h;
end
hold on
plot(x,ynum);
plot(x,y(x))
hold off
grid on;
Kristina
Kristina le 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 le 3 Oct 2022
Well, I don't understand what you mean, but you're welcome ! :-)

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by