Plot polynomial using Eueler's method

1 visualizzazione (ultimi 30 giorni)
E
E il 8 Ott 2022
Modificato: E il 9 Ott 2022
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.

Risposta accettata

Davide Masiello
Davide Masiello il 8 Ott 2022
Modificato: Davide Masiello il 8 Ott 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
yp = 
You'll need this symbolic derivative to be turned into a matlab function, which you can to like this
dydx = matlabFunction(yp)
dydx = function_handle with value:
@(x)x.*2.0+x.^2.*3.0-1.2e+1
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 Commenti
E
E il 8 Ott 2022
Modificato: E il 9 Ott 2022
Thank you so much everyone for your helpful feedback. Seeing my code not working and not knowing why was truly frustrating. Matlab is a challenge. I read your comments and i think i understand where my code was running into issues. Thank you again for your help on this.
Steven Lord
Steven Lord il 9 Ott 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.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by