MATLAB: Function functions of fixed-point iteration

fixed-fixed-point iterationfunctionsmatlab function

Hello,
I'm trying to make function functions, but I have an error in the last row and I don't know that's wrong:
clc;
close all;
clear all;
syms x;
fun=@(x)-0.0641*x^3+1.0889*x^2-3.8260*x+0.6364;
n=input('Enter the number of decimal places:');
x0 = input('Enter the intial approximation:');
[t]=F[@fun, x0,n]
My function F is:
function [t] = F(fun, x0, n)
% Detailed explanation goes here
g=diff(fun);
epsilon = 5*10^-(n+1)
i=1;
rng(0,'twister');
alpha = -2/vpa(subs(g,x,x0));
x_current = x0;
while i~=200
phi_of_x_at_x_current= x_current + (alpha*vpa(subs(fun,x,x_current)));
err=abs(phi_of_x_at_x_current-x_current);
if abs(1+alpha*vpa(subs(g,x,x_current)))>=1
alpha = -1*(2/vpa(subs(g,x,x0))*rand);
i=1;
elseif err<epsilon
break
end
x_current = phi_of_x_at_x_current;
i=i+1;
end
phi_of_x_at_x_current = phi_of_x_at_x_current - rem(phi_of_x_at_x_current,10^-n);
fprintf('Answer: %f \n',phi_of_x_at_x_current);
end

Best Answer

Hi,
You were almost there and just overlooked at one point with: g=diff(fun); that requires symbolic differentiaion w.r.t the variable x. Another very minor point is output variable name t that was assigned but not given any output value within F.m. I have chosen phi_of_x_at_x_current that can be changed to any output calc's from F.m
Here is the corrected codes. Note that I have done some name changes not to get confused with fun and g which are substitute with FF and G. I like upper cases for the sake of visibility.
function phi_of_x_at_x_current = F(FF, x0, n)
% Detailed explanation goes here
syms x
G=diff(FF, x);
epsilon = 5*10^-(n+1);
i=1;
rng(0,'twister');
alpha = -2/vpa(subs(G,x,x0));
x_current = x0;
while i~=200
phi_of_x_at_x_current= x_current + (alpha*vpa(subs(FF,x,x_current)));
err=abs(phi_of_x_at_x_current-x_current);
if abs(1+alpha*vpa(subs(G,x,x_current)))>=1
alpha = -1*(2/vpa(subs(G,x,x0))*rand);
i=1;
elseif err<epsilon
break
end
x_current = phi_of_x_at_x_current;
i=i+1;
end
phi_of_x_at_x_current = phi_of_x_at_x_current - rem(phi_of_x_at_x_current,10^-n);
fprintf('Answer: %f \n',phi_of_x_at_x_current);
end
clc;
close all;
clear variables
syms x
FF=@(x)-0.0641*x^3+1.0889*x^2-3.8260*x+0.6364;
n=input('Enter the number of decimal places: ');
x0 = input('Enter the intial approximation: ');
OUT = F(FF, x0, n);
>> Enter the number of decimal places: 3
>> Enter the intial approximation: 55
Answer: 12.188000
Good luck.