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

1 回表示 (過去 30 日間)
Elchin Ahmadov
Elchin Ahmadov 2013 年 12 月 8 日
回答済み: Anurag Ojha 2024 年 6 月 19 日
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 Center および File ExchangeInterpolation についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by