Plot polynomial using Eueler's method

1 view (last 30 days)
E
E on 8 Oct 2022
Edited: E on 9 Oct 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.

Accepted Answer

Davide Masiello
Davide Masiello on 8 Oct 2022
Edited: Davide Masiello on 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
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 Comments
E
E on 8 Oct 2022
Edited: E on 9 Oct 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 on 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.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!