i keep getting " root' requires Symbolic Math Toolbox. Error in newtonbisection (line 46) fprintf("Optimal root of the given function: %f\n\n",root)". how to fix that? thanks

1 view (last 30 days)
%define the function
f = @(x) tanh(x);
dfun = @(x) 1-tanh(x)^2;
a = -10;
b = -15;
s = 0.1;
count1 = 0;
while (b-a)>s*(b-a)
m = (a+b)/2;
if fun(a)*f(m)<0
b = m;
else
a = m;
end
count1=count1+1;
end
%get the narrow interval
na = a;
nb = b;
fprintf('using bisection method, narrow interval obtained after %d iterations:[%f.%f]\n\n',count1,na,nb)
m = (a+b)/2; %m is the root of the narrowed interval
eps = 1;
tolerence = e^-6;
count2=0;
%Now implement Newton's method
while eps>tolerence
%calculate the root according to Newtons method
root = m-(fun(m)/dfun(m));
count2 = count2+1;
%Now check whether the root is in the narrow interval or not
if root<na || root>nb
%if out of the narrow interval then switch back to bisection method
root = (na+nb)/2;
fprintf("Solution by Newton's method jumped out of the narrow interval after %d iteration\n so again switching back to bisection method\n\n",count2);
if fun(na)*fn(root)<0
nb = root;
else
na = root;
end
end
%calculate the difference
eps = abs (root-m);
m = root;
end
%Finally root is the final root;
fprintf("Optimal root of the given function: %f\n\n",root)
fprintf('Second while loop is executed %d times\n\n\n',count2)
[SL: formatted code as code]

Answers (1)

Steven Lord
Steven Lord on 14 Nov 2021
What value is given to the variable root in the code if the while condition is not satisfied?
while eps>tolerence
The answer is none, nothing assigns any value to that variable (and so the variable does not exist.) In that case MATLAB needs to figure out what root on the next to last line of your code refers. Since there is a function named root in Symbolic Math Toolbox, MATLAB decides that you intended to call that function with zero input arguments.
  2 Comments
Steven Lord
Steven Lord on 15 Nov 2021
Define the variable named root before the loop to some "placeholder" value.
Rename the variable.
If you intended the tolerance to be one times ten to the -6th, write it as 1e-6 instead of writing it in such a way that it could use a variable named e.Alternately you may have intended it to be exp(-6).

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by