How can i fix the Error at 1

I cannot run my code because it says syntax error at "1" in line 2
f=@(x)+(x^3)-(x^1);
fd=@(1)+(3(x^2))+(x^-2));
a= round (input ('Enter Your Initial Value(x) :'),1);
tol = 0.0002; % 4 decimal places
fa = round(feval (f,a),1);
fda = round(feval (fd,a),1);
al = round((a-(fa/fda)),1);
error = round(abs((al-a)/al),1);
iter =0;
disp (' n Xn F(x) F(x) Xn+1 Error') disp (' -----------------------------------------------------------')
while (error>= tol)
iter = iter+1;
al = round(a-(fa/fda),1);
fal = round(feval(f,al),1);
fdal = round((feval(fd,al)),1);
error = round(abs(((al-a)/al)*100),1);
fprintf('%2i\t %f\t %f\t %f\t %f\t %f\t \n',iter,a,fa,fda,al,error)
if (error>=tol) a = al; fa = fal; fda = fdal;
end end

Answers (2)

fd=@(x) (1)+(3*(x.^2))+(x.^-2));
You probably mean this instead:
fd=@(x)+(3*(x^2))+(x^-2);
% ^ ^ ^
% | add the * remove the extra parenthesis
% x instead of 1
On the other lines there are also several issues. Below is my attempt at debugging your code. It runs for a=100, although I can't tell if the output makes sense.
f=@(x) (x^3)-(x^1);
fd=@(x) (1)+(3*(x^2))+(x^-2);
a= round (input ('Enter Your Initial Value(x) :'),1);
tol = 0.0002; % 4 decimal places
fa = round(f(a),1);
fda = round(fd(a),1);
al = round((a-(fa/fda)),1);
error = round(abs((al-a)/al),1);
iter =0;
disp (' n Xn F(x) F(x) Xn+1 Error')
disp (' -----------------------------------------------------------')
while (error>= tol)
iter = iter+1;
al = round(a-(fa/fda),1);
fal = round(f(al),1);
fdal = round((fd(al)),1);
error = round(abs(((al-a)/al)*100),1);
fprintf('%2i\t %f\t %f\t %f\t %f\t %f\t \n',iter,a,fa,fda,al,error)
if (error>=tol)
a = al; fa = fal; fda = fdal;
end
end

4 Comments

Thank you for the answer. i can run the code but i cannot get the answer as i expected. it might be because of my interpretation of the question given to coding in MATLAB. Just informing you that this is the question given: By using MATLAB Coder, find the positive root of f(x) = 1+x^3 - 1/x using Newton-Raphson Method. Plot y=1+x^3 y=1/x in the same plane.
Rik
Rik on 13 May 2020
Edited: Rik on 13 May 2020
Then you probably mean
f=@(x) 1 + (x.^3) - (x.^-1);
% ^ ^
% these dots are to enable array operations
And if fd is intended as the derivative of f, you should do remove the 1+ term:
fd=@(x) (3*x.^2) + (x.^-2);
Your code is also uncommented, so without looking up the Newton-Raphson method I can't tell in which step you have an error. Try to write the algorithm in comments first and then write the code for each step.
but 1 is there because its the derivative of x what do you mean by removing the 1+?
@Robbie, there is no x in the original function (only a cube and reciprocal), so why would there be a 1+ in the derivative?

Sign in to comment.

Categories

Products

Release

R2020a

Tags

Asked:

on 13 May 2020

Commented:

Rik
on 13 May 2020

Community Treasure Hunt

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

Start Hunting!