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

조회 수: 7 (최근 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