MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by John on 24 Dec 2012

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.*

Answer by Matt J on 24 Dec 2012

Edited by Matt J on 24 Dec 2012

Accepted answer

If the goal is to find a root of func, then the update formula for Newton's method should be

xn=xn-func(xn)./Dfunc(x)

This method of accumulating the solutions

veczero=zeros(1,counter)+xn;

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.

vec(counter)=xn;

Show 1 older comment

Matt J on 24 Dec 2012

I don't have the Symbolic Math Toolbox, but I don't know why

dfunc = matlabFunction(diff(func)); %func is class sym

wouldn't have worked.

bym on 24 Dec 2012

seems to work fine for me... (R2008b)

matlabFunction(diff(func))

ans =

@(x)3.*x.^2+8

## 0 Comments