Section
2.2 Fixed-Point Iterations –MATLAB code
1.
• One way to define function in the command window is:
>> f=@(x)x.^3+4*x.^2-10
f =
@(x)x.^3+4*x.^2-10
To evaluate function value at a point:
>> f(2)
ans =
14
or
>> feval(f,2)
ans =
14
• abs(X) returns the absolute value. If X is complex, abs(X) returns
the complex magnitude.
>> x=-3
x =
-3
>> abs(x)
ans =
3
>> y=1-2i
y =
1.0000 - 2.0000i
>> abs(y)
ans =
2.2361
• For ‘fprintf’’, please see ‘doc fprintf’ for different options
•
2. Matlab Code: (in MATLAB editor)
( you may adjust some of the variables according to the given problem)
function [ iter ] = myfixed2(g, x0, tol,n)
%UNTITLED3 Summary of this function goes here
% Detailed explanation goes here
iter=0;
u=feval(g, x0);
err=1; % It just set up a big number
disp('-------------------------------------------')
disp('iter x g(x) |xn+11-xn| ')
disp('-------------------------------------------')
fprintf('%2.0f %12.6f %12.6f\n', iter, x0,u)
while (err>tol)&(iter<=n)
x1=u;
err=abs(x1-x0);
x0=x1;
u=feval(g, x0);
iter=iter+1;
fprintf('%2.0f %12.6f %12.6f %12.8f\n', iter,x0,u,err)
end
if(iter>n)
display('Method failed to converge')
end
end
For example.
>> f2
f2 =
@(x)x-(x.^3+4*x.^2-10)/(3*x.^2+8*x)
>> myfixed2(f2,2.5,10^(-6),100)
-------------------------------------------
iter x g(x) |xn+11-xn|
-------------------------------------------
0 2.500000 1.709677
1 1.70967742 1.41166231 0.79032258
2 1.41166231 1.36625216 0.29801511
3 1.36625216 1.36523053 0.04541015
4 1.36523053 1.36523001 0.00102164
5 1.36523001 1.36523001 0.00000051
ans =
5