Implementing Euler's method for a 1D system

1 次查看(过去 30 天)
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).

采纳的回答

KSSV
KSSV 2022-10-3
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 个评论
Kristina
Kristina 2022-10-3
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 2022-10-3
Well, I don't understand what you mean, but you're welcome ! :-)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Numerical Integration and Differential Equations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by