MATLAB: I need to write a program that a user inputs a function, the function’s derivative, and their initial guess of the root, and then with the Newton Raphson method find the root (or a number with a very small error close to the root).

homeworkinline()newtonnewton raphson

I need to write a program that a user inputs a function, the function's derivative, and their initial guess of the root, and then with the Newton Raphson method find the root (or a number with a very small error close to the root). We were told to use inline(), but I'm completely lost, any help would be great.
func = inline('f','x');
dfunc = inline('df','x');
f = input('Enter a function (MATLAB COMPATIBLE) in terms of x:\n', 's');
df = input('Enter the derivative of that function (MATLAB COMPATIBLE):\n', 's');
xr = input('Enter your initial guess of the root:\n');
iter=0;
while(1)
xold=xr;
xr= xr-func(xr)/dfunc(xr);
iter=iter+1;
if xr~=0, ea=abs((xr-xrold)/xr)*100;end
end

Best Answer

m - use inline after you have requested the function expression from the user. For example,
fExpr = input('Enter a function (MATLAB COMPATIBLE) in terms of x:\n', 's');
f = inline(fExpr);
dfExpr = input('Enter the derivative of that function (MATLAB COMPATIBLE):\n', 's');
df = inline(dfExpr);
For example, the user could enter a function string as
x^2
and its corresponding derivative as
2*x
Then the inline objects/functions f and df could be used to evaluate any input as
>> f(3)
ans =
9
>> df(3)
ans =
6
Try incorporating the above into your algorithm.
Note also that your algorithm appears to be incomplete. How do you expect to break out once the root has been found? What is ea used for? You will need a maximum number of iterations check on your while loop so that you don't get stuck in an infinite loop. Also, since manipulating floating point numbers, you cannot compare them to zero but rather you will need to use a tolerance check to see if the value is "close" to zero. Since this is homework, I will leave this as an exercise for you to complete.