Plot polynomial using Eueler's method
18 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Davide Masiello
le 8 Oct 2022
Modifié(e) : Davide Masiello
le 8 Oct 2022
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 commentaires
Steven Lord
le 9 Oct 2022
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Formula Manipulation and Simplification dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
