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)
Initial guess = 5.000000
% 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
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
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

采纳的回答

Dyuman Joshi
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 个)

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by