Write a MATLAB function, called f ixed_point_iteration that inputs a function, g
ID: 3888679 • Letter: W
Question
Write a MATLAB function, called f ixed_point_iteration that inputs a function, g, an initial guess x_0, an error tolerance, tol, and a maximum number of iterations, N, and outputs the fixed point of g, obtained using the fixed point iteration, starting with x_0. Your function should have an error defined by E = |x_n - x_n - 1|, and stop when the error is less than the tolerance, or if the number of iterations exceeds N- whichever happens first. Your function header should look something like: function [c, n, err] = fixed_point_iteration (g, x0, tol, N)Explanation / Answer
Here is the solution for the same. It has been commented for your reference.
Note, the text following '%' symbol is a comment in matlab
function [c,n,err] = fixed_point_iteration(g,x0,tol,N)
% here g is a function, x0 is an initial guess
% tol is the tolerance level and N is number of iterations
intermediate_value = 0; % we use a variable to store intermediate function values
for i=1:N %loop from 1 to N for N iterations
intermediate_value = g(x0); %evaluate function at x0
if abs(intermediate_value - x0) < tol %check if absolute difference is less than tolerance
break; %if difference less than tolerance, then break.
end
x0 = intermediate_value; %update the guess value, to intermediate value
end
n = i;
err = abs(intermediate_value - x0);
c = intermediate_value;
Useage example:
%define some function some_random_function, which given an x returns some y after some computation
function [y] = some_random_function(x)
y=10/(x*x*x - 1);
%create function handler for that function. Function handlers are created by putting '@' sign infront of function name
g = @some_random_function
[a,b,c] = fixed_point_iteration(g, 2, 0.1, 4)
we get output as:
a =
-10.0035
b =
4
c =
10.0743
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.