Finding real root of Newton's cubic
8 views (last 30 days)
Show older comments
f = @(x) (x^5)-(2*x)-5;
dff = @(x) (3*x^2)-2;
x(0) = 1;
itr_num = 10;
TOL = 1E-6;
x = zeros(itr_num+1, 1);
x(1) = x^0;
val_n = 2;
n_fin = (itr_n <= itr_num+1)
while (val_n <= itr_num+1)
fe = f(x)*(val_n-1);
dffe = dff(x(val_n-1));
xval_n = (x(val_n-1) - (fe/dffe));
if (abs(fe) <= TOL)
n_fin = val_n;
break;
end
val_n = val_n+1;
end
fprintf('The approximate root is %f',x(val_n))
figure('color','white')
plot(0:n_fin-1,x(1:n_fin,'0-'));
title('f(x) = (x^3)-(2*x)-5');
xlabel('Iteration', 'Fontsize',16);
ylabel('value');
Now when I run the code it says 'Array indices must be positive integers or logical values'. How do I fix this as it doesn't give a specific line.
0 Comments
Answers (2)
James Tursa
on 7 Dec 2018
Edited: James Tursa
on 7 Dec 2018
The third line:
x(0) = 1;
You have a 0 index. You need to start your indexing with 1, not 0.
You've got other issues with your code also. E.g., take these lines:
x = zeros(itr_num+1, 1);
x(1) = x^0;
Given that you have now defined x as a vector of 0's, what were you expecting the x^0 calculation to give you? Does it make sense to do that calculation and then assign the result to the x(1) element?
And then look at this line:
fe = f(x)*(val_n-1);
Here you don't index into x, but pass the whole vector into your f( ) function. That isn't going to do what you want either, and will need to be fixed.
And take a look at your function and derivative definitions:
f = @(x) (x^5)-(2*x)-5;
dff = @(x) (3*x^2)-2;
Does dff really look like the derivative of f to you?
2 Comments
James Tursa
on 11 Dec 2018
I've given you several pointers already. We are waiting for you to implement them and then get back to us on your progress and where you are still having problems.
See Also
Categories
Find more on Matrix Computations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!