Can't quite figure out why my syms is giving me an error
조회 수: 2 (최근 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!