Can't quite figure out why my syms is giving me an error
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Patrick
am 1 Mär. 2024
Bearbeitet: Dyuman Joshi
am 1 Mär. 2024
% 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 Kommentare
Akzeptierte Antwort
Dyuman Joshi
am 1 Mär. 2024
Bearbeitet: Dyuman Joshi
am 1 Mär. 2024
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Symbolic Math Toolbox finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!