Chebyshev method for finding root

12 views (last 30 days)
Milind Amga on 2 Oct 2020
Commented: Milind Amga on 2 Oct 2020
This code is for finding root of an equation. But this runs into an error saying, unable to convert expression into double array. The error occurs because of the improper use of function handle in g,M,N.
If I take input 'f' as a function handle then I cannot differentiate it and if I take 'f' as just an expression then I cannot convert it into a function handle.
Can someone guide me in the right direction?
function [root,iteration] = chebyshev(a,f) %please input function in terms of y=f(x)(x as independent variable)
% Do not input function as function handle
if nargin<1 % check no of input arguments and if input arguments is less than one then puts an error message
fprintf('Error! Atleast one input argument is required.');
return;
end
if nargin<2 % check no of input arguments and if input arguments is less than two then puts a=0
a=0;
end
g = @(x) f;
M = @(x) diff(f,'x');
N = @(x) diff(f,'x',2);
temp = false;
i =1 ;
x(1) = a;
count = 0;
while temp == false
A = g(x(i));
B = M(x(i));
C = N(x(i));
D = double((A/B) + 0.5*((A^2)*C/(B^3)));
x(i+1) = x(i) - D;
if x(i+1)-x(i) == 0
temp = true;
root = x(i-1);
iteration = i-1;
return;
end
i = i+1;
count = count + 1;
end
end

Walter Roberson on 2 Oct 2020
% Do not input function as function handle
The code says right there not to pass in a function handle for f.
M = @(x) diff(f,'x');
That will fail for function handle f.
You would need to be passing in a symbolic expression or symbolic function to have a chance.
Milind Amga on 2 Oct 2020
Yes, I totally understood what's causing the error but couldn't think of any solution.