You are on page 1of 19

Matlab

Non Linear& Differentiation

Plotting

Use fplot command

example fplot('x^3+x-3',[-2 2]),grid

M-file (function) for Newton Method


Create new M-File in command window >> edit newton function in editor function r = newton (f_str,df_str, x) Save the file (File > Save) newton.m

function r = newton (f_str,df_str,x)


f=inline (f_str); df =inline(df_str); steps=0; tol=0.00005; error=1; while (error>tol)&(steps < 20) xold=x; x=x-f(x)/df(x); steps=steps+1; disp([x f(x)]); error=abs((x-xold)); end r=x; if error <=tol disp('Zero Found') else disp('Zero Not found') end

Call the function in command window >> newton('x^3+x-3','3*x^2+1',0) Output

fzero
Locating root using fzero function Command window >>x0= initial value >> x= fzero(inline(f),x0) Example >> x0=0; >> x=fzero(inline('x^3+x-3'),x0)

Output >> x0=0; x=fzero(inline('x^3+x-3'),x0)

x= 1.2134

Numerical Differentiation
M-file (scripts) Create the M-file in window command >> edit Write the Matlab statement for numerical differentiation using 2 point forward and 2 point backward difference in editor

Save the file (File > Save) dif1.m Run the scripts in the command window >>dif1

Modify the scripts to add other numerical differentiation


three

point centre difference centre =(f(x==(i+h))-f(x==(i-h)))/(2.*h); disp(sprintf('\n\tf''(1.05)=%g\t(centre formula)',centre));

diff command
2 point forward >> x=[1.05 1.10]; >> y=[1.02470 1.04881]; >> d=diff(y)./diff(x)

d= 0.4822

2 point backward >>x=[1 1.05]; >> y=[1.0000 1.02470 ]; >> d=diff(y)./diff(x)

d= 0.4940

3 point Centre difference >> x=[1 1.10]; >> y=[1.0000 1.04881]; >> d=diff(y)./diff(x)

d= 0.4881

Tutorial Lab

Page 23

Each group choose 1 function only and determine root using newton method

Page 27
Each

group choose 1 function and -determine f ( 0.03 ) with h=0.01 using


two point forward difference two point backward difference three point centre difference Three point centre difference

-determine f ( 0.03 ) with h=0.01 using

You might also like