Clear Filters
Clear Filters

i try to do quadratic interpolation with 3 initial guesses. when i run the code it do nothing

3 views (last 30 days)
d=input('Please enter a function f(x): ');
x0=input('Please give a initial guess of x0: ');
x1=input('Please give a initial guess of x1: ');
x2=input('Please give a initial guess of x2: ');
signum=input('Please enter the prespecified error: ');
f=inline(d);
i=1;
x3=(f(x0)*(x1^2-x2^2)+f(x1)*(x2^2-x0^2)+f(x2)*(x0^2-x1^2))/(2*f(x0)*(x1-x2)+2*f(x1)*(x2-x0)+2*f(x2)*(x0-x1));
x(i)=x3;
error(i)=9999;
es=(0.5*10^(2-signum));
while error(i)>=es
x(i+1)=(f(x0)*(x1^2-x2^2)+f(x1)*(x2^2-x0^2)+f(x2)*(x0^2-x1^2))/(2*f(x0)*(x1-x2)+2*f(x1)*(x2-x0)+2*f(x2)*(x0-x1));
a=x(i+1);
if f(a)>f(x0)
if f(a)>f(x2)
x0=x1;
x1=x(i+1);
x(i+1)=(f(x0)*(x1^2-x2^2)+f(x1)*(x2^2-x0^2)+f(x2)*(x0^2-x1^2))/(2*f(x0)*(x1-x2)+2*f(x1)*(x2-x0)+2*f(x2)*(x0-x1));
elseif f(a)<f(x2)
x2=x1;
x1=x(i+1);
end
end
error(i+1)=abs((((x(i+1)-x(i))/(x(i+1)))*100));
i=i+1;
end

Answers (1)

Anurag Ojha
Anurag Ojha on 19 Jun 2024
Hey
The code you provided seems to have some syntax errors. Additionally, the use of the inline function is not recommended as it has been removed in recent versions of MATLAB.
Instead, you can define your function using anonymous function syntax. Here's an updated version of your code:
d = input('Please enter a function f(x): ');
f = @(x) eval(d);
x0 = input('Please give an initial guess of x0: ');
x1 = input('Please give an initial guess of x1: ');
x2 = input('Please give an initial guess of x2: ');
signum = input('Please enter the prespecified error: ');
i = 1;
x(i) = (f(x0)*(x1^2-x2^2) + f(x1)*(x2^2-x0^2) + f(x2)*(x0^2-x1^2)) / (2*f(x0)*(x1-x2) + 2*f(x1)*(x2-x0) + 2*f(x2)*(x0-x1));
error(i) = 9999;
es = 0.5 * 10^(2-signum);
while error(i) >= es
x(i+1) = (f(x0)*(x1^2-x2^2) + f(x1)*(x2^2-x0^2) + f(x2)*(x0^2-x1^2)) / (2*f(x0)*(x1-x2) + 2*f(x1)*(x2-x0) + 2*f(x2)*(x0-x1));
a = x(i+1);
if f(a) > f(x0)
if f(a) > f(x2)
x0 = x1;
x1 = x(i+1);
x(i+1) = (f(x0)*(x1^2-x2^2) + f(x1)*(x2^2-x0^2) + f(x2)*(x0^2-x1^2)) / (2*f(x0)*(x1-x2) + 2*f(x1)*(x2-x0) + 2*f(x2)*(x0-x1));
elseif f(a) < f(x2)
x2 = x1;
x1 = x(i+1);
end
end
error(i+1) = abs(((x(i+1)-x(i))/x(i+1)) * 100);
i = i + 1;
end
This code should now run without any syntax errors. However, please note that the quadratic interpolation algorithm you are using may not always converge or produce accurate results. It is recommended to use more robust optimization algorithms provided by MATLAB's Optimization Toolbox for such tasks.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!