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

2 次查看(过去 30 天)
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

回答(1 个)

Anurag Ojha
Anurag Ojha 2024-6-19
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.

类别

Help CenterFile Exchange 中查找有关 Spline Postprocessing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by