Erro in calling function using horner()
3 views (last 30 days)
Show older comments
I wrote the following code to fild the roots of a given function. In program, the example function ig given by f(x) = x^3-6x^3+11x-6. When I compile the code the following messages appears:
Incorrect number or types of inputs or outputs for function 'horner'.
Error in test>newtonhorner (line 34)
[pz,b] = horner(a,x);
Error in test (line 4)
a = [1 -6 11 -6]; [x,niter]=newtonhorner(a,0,1.e-15,100);
How can I solve this? Thanks if anyone can help!
My code:
a = [1 -6 11 -6]; [x,niter]=newtonhorner(a,0,1.e-15,100);
function [roots , iter]= newtonhorner(a,x0,tol,nmax)
%NEWTONHORNER Newton - Horner method
% [roots , ITER]= NEWTONHORNER(A,X0) computes the roots of
% polynomial
% P(X) = A(1)*X^N + A(2)*X^(N-1) + ... + A(N)*X +
% A(N+1)
% using the Newton - Horner method starting from the
% initial datum X0. The method stops for each root
% after 100 iterations or after the absolute value of
% the difference between two consecutive iterates is
% smaller than 1.e-04.
% [roots , ITER]= NEWTONHORNER(A,X0 ,TOL , NMAX) allows to
% define the tolerance on the stopping criterion and
% the maximal number of iterations.
if nargin == 2
tol = 1.e-04; nmax = 100;
elseif nargin == 3
nmax = 100;
end
n=length(a)-1;
roots = zeros (n,1);
iter = zeros(n,1);
for k = 1:n
% Newton iterations
niter = 0; x = x0; diff = tol + 1;
while niter <= nmax & diff >= tol
[pz,b] = horner(a,x);
[dpz,b]= horner(b,x);
xnew = x - pz/dpz;
diff = abs(xnew -x);
niter = niter + 1;
x = xnew;
end
if niter >= nmax
fprintf('Fails to converge within maximum ',...
'number of iterations\n ');
end
% Deflation
[pz ,a] = horner(a,x); roots(k) = x; iter(k) = niter;
end
return
end
0 Comments
Accepted Answer
Torsten
on 28 Nov 2022
Edited: Torsten
on 28 Nov 2022
I don't understand what you intend by using the lines
[pz,b] = horner(a,x);
[dpz,b]= horner(b,x);
[pz ,a] = horner(a,x)
They will error because of two reasons:
a and b must be symbolic polynomials.
"horner" has only one output, namely the input polynomial in horner form.
0 Comments
More Answers (0)
See Also
Categories
Find more on Tables 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!