Plot polynomial using Eueler's method
1 回表示 (過去 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 件)
参考
カテゴリ
Help Center および File Exchange で Polynomials についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!