I have used a while loop in the algorithm. Once the absolute error is less than the specified tolerance (tol), the while loop stops and the function is expected to output one solution, even though many solutions exist. I have tried x^3 + 8x -18=0 with a starting guess 2. It should take two iterations to obtain the solution, but I cannot figure out why the computational perfomance is very slow when executing the function.
function moisolver syms x func=input('Enter the function f(x) which is equal zero:'); xn=input('Enter your initial guess:');
% The function func is switched to a function handle class Dfunc=jacobian(func,x); Dfunc=matlabFunction(Dfunc);
% The derivative dfuncd is switched to a function handle class dfuncd=diff(func); Dfuncd=jacobian(dfuncd,x); Dfuncd=matlabFunction(Dfuncd);
% The tolerance is defined. The abs_error, counter and the vector % storing the approximated solutions during the iteration process, are % initialized tol=10^(-1); abs_error=1; counter=1; vec=xn;
while abs_error>=tol counter=1+counter; % xn is the iterative solution xn=xn-Dfunc(xn)/Dfuncd(xn); % An expanding vector veczero is added with xn veczero=zeros(1,counter)+xn; % The former solutions are redefined in veczero. Notice that the % last element in veczero is defined as the last obtained solution veczero(1:counter-1)=vec; % vec is redefined vec=veczero; % The absolute error is calculated abs_error=abs(vec(end)-vec(end-1)); end solution=vec(end); fprintf('The solution is %.2f.\n',solution) fprintf('The computer generated %d iterations to obtain the solution.\n',counter)
No products are associated with this question.
If the goal is to find a root of func, then the update formula for Newton's method should be
This method of accumulating the solutions
is also hurting you in multiple ways. You should be pre-allocating memory for vec prior to the loop. You should also not be using vector addition to append xn to vec, when a scalar assignment operation will do the same thing much less expensively.
Play games and win prizes!Learn more