Can't quite figure out why my syms is giving me an error
1 次查看(过去 30 天)
显示 更早的评论
% Define the function in symbolic form:
syms x
f = exp(-0.5*x)*(4-x)-2 ;
% Differentiate f(x) in x:
Df = diff(f,x) ;
% Convert f and Df to function handle:
f = matlabFunction(f) ;
Df = matlabFunction(Df) ;
% Define initial guess:
Xest = 5 ;
fprintf('Initial guess = %f\n', Xest)
% Run a for loop for 10 iterations:
for i = 1:10
% Call the function for next approximation:
Xest = NewtonSol(f, Df, Xest);
fprintf('i = %d, Xest = %f\n', i, Xest)
end
function Xs = NewtonSol(Fun, FunDer, Xest)
% Newton-Raphson formula
Xs = Xest - Fun(Xest)/FunDer(Xest) ;
end
Output
I should be getting this as an output
Initial guess = 5.000000 i = 1, Xest = -45.729976 i = 2, Xest = -43.807300 i = 3, Xest = -41.887610 i = 4, Xest = -39.971139 i = 5, Xest = -38.058150 i = 6, Xest = -36.148939 i = 7, Xest = -34.243841 i = 8, Xest = -32.343235 i = 9, Xest = -30.447556 i = 10, Xest = -28.557302
but for some reason syms has an error message
0 个评论
采纳的回答
Dyuman Joshi
2024-3-1
编辑:Dyuman Joshi
2024-3-1
The error is not with the symbolic part of your code, but how your code is arranged/structured.
If any function(s) is(are) defined in a script file, it(they) must be defined at the end of the file, after all the script code.
Your code works after making that change (see above).
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!