Plot polynomial using Eueler's method
18 次查看(过去 30 天)
显示 更早的评论
syms x;
y=x.^3 + x.^2- 12*x; %polynomial function
dy= diff(y,x)%derivative of y
N=100;
h=0.1;
x=-4:0.1:3;
y(1)=-10;
y=zeros(size(x));
EM=[]; %empty array to store values
for n=1:N
y(n+1)=y(n)+h*dy(n);
x(n+1)=n*h;
EM(x,y)=[x,y];
end
plot(EMsub,"r-")
Hello, this is the code that i have so far. I have tried writing a code to plot f(x)=x^3+x^2-12x using Euler's method in matlab. I can seem to figure out why the code is not running. At line 12 i keep getting the following error:
Error using symengine
Unable to convert expression containing symbolic variables into double array. Apply 'subs' function first to substitute values for variables.
I am not exactly sure how to fix this error or what is wrong. Could someone explain why its not working and what i am doing wrong here? Any help would be appreciated.
0 个评论
采纳的回答
Davide Masiello
2022-10-8
编辑:Davide Masiello
2022-10-8
so, initially, you calculate the analytical derivative of the function using the symbolic environment
syms x
y = x^3+x^2-12*x; % polynomial function
yp = diff(y,x) % symbolic derivative of y
You'll need this symbolic derivative to be turned into a matlab function, which you can to like this
dydx = matlabFunction(yp)
Now, you can solve the ODE represented by dydx using Euler's method.
h = 0.1;
xn = -5:h:5;
yn = zeros(size(xn));
yn(1) = -40;
for idx = 2:length(xn)
yn(idx) = yn(idx-1)+h*dydx(xn(idx-1));
end
Now, you can plot both numerical and analytical solutions for comparison
fplot(y)
hold on
plot(xn,yn,'k--')
legend('Analytical solution','Euler''s method')
5 个评论
Steven Lord
2022-10-9
Since it sounds like you're new to MATLAB, I suggest you start with the free MATLAB Onramp tutorial to quickly learn the essentials of MATLAB.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
