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

15 views (last 30 days)
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);

Accepted Answer

Matt J
Matt J on 21 Sep 2021
Edited: Matt J on 21 Sep 2021
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);

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!