I dont understand why my table is displaying 1x1 sym and not a numerical value

조회 수: 20 (최근 30일)
This is my code. We are coding newton-rhapson method and the code is working fine, but I cant seem to figure out how to add a table with the actual values showing at the end which is required on the assignment.
clc;
close all;
clear;
syms x;
syms a1;
f=0.4*sin(2*pi*x^2)*exp(x)-1; %Function
g=diff(f); %Calculate derivative
n=input('Enter the number of decimal places:');
error = 1*10^-(n+2);
x0 = input('Enter intial approximation:');
for i=1:100
f0=vpa(subs(f,x,x0)); %Calculating the value of function at x0
f0_der=vpa(subs(g,x,x0)); %Calculating the value of function derivative at x0
y=x0-f0/f0_der; % The Formula
err=abs(y-x0);
if err<error %checking the amount of error at each iteration
break
end
x0=y;
end
y = y - rem(y,10^-n); %Displaying upto required decimal places
fprintf('The Root is : %f \n',y);
fprintf('No. of Iterations : %d\n',i);

채택된 답변

Matt J
Matt J 2021년 9월 21일
편집: Matt J 2021년 9월 21일
You seem to be under the impression that vpa() converts a sym to a number. What you really want to do is use matlabFunction() to pre-convert f and g to actual numeric functions:
n=input('Enter the number of decimal places:');
stopTol = 1*10^-(n+2);
x0 = input('Enter intial approximation:');
syms x;
f=0.4*sin(2*pi*x^2)*exp(x)-1; %Function
g=diff(f); %Calculate derivative
f=matlabFunction(f);
g=matlabFunction(g);
for i=1:100
y=x0-f(x0)/g(x0); % The Formula
if abs(y-x0)<stopTol ,break; end
x0=y;
end
y = y - rem(y,10^-n); %Displaying upto required decimal places
fprintf('The Root is : %f \n',y);
fprintf('No. of Iterations : %d\n',i);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Conversion Between Symbolic and Numeric에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by