How can I change the definition of x to find the value of y(3.5112)( i mean y(x1)) for this question ?

1 次查看(过去 30 天)
Y

回答(1 个)

Torsten
Torsten 2022-8-1
I don't know if it helps:
%%main func
clear all;
close all;
clf;
clc;
% Define the function
x = linspace(-10,10,100);
f = @Goldenfunc;
y = f(x);
figure(1)
plot(x,y,'k',LineWidth=2), hold on
xr = GoldenSection(0,10,f);
plot(xr,'bo')
function [xr] = GoldenSection(xL,xU,y)
N = 200;
GR = (sqrt(5)-1) / 2; % Golden Ratio Number
d = GR * (xU-xL);
x1 = xL + d;
x2 = xU - d;
fx1 = y(x1); % y(x1) alamıyor çünkü x1 positive integer değil
fx2 = y(x2);
for i=1:N
if fx1 > fx2 % Move lower bound to x1
xL = x1;
fL = fx1;
x1 = x2; % update x1
fx1 = fx2;
d = GR * (xU - xL); %update d & x2
x2 = xL + d;
fx2 = y(x2);
elseif fx1 < fx2
xU = x2;
fU = fx2;
x2 = x1;
fx2 = fx1;
d = GR * (xU - xL); %update d & x1
x1 = xU - d;
fx1 = y(x1);
else
xL = (x1 + x2) / 2;
xU = xL;
end
end
xr = (x1 + x2) / 2;
%plot(xr,'ko')
end
function y = Goldenfunc(x)
%x = linspace(0,10,100);
y = x.^2 - 6*x + 15;
%plot(x,y);
%hold on
end
  1 个评论
Torsten
Torsten 2022-8-1
编辑:Torsten 2022-8-1
This would me my suggestion:
%%main func
% Define the function
x = linspace(-10,10,100);
y = f(x);
figure(1)
plot(x,y,'k',LineWidth=2)
hold on
a = 0;
b = 10;
fun = @f;
tol = 1e-8;
x = GoldenSection(a,b,fun,tol);
plot(x,f(x),'o')
function x = GoldenSection(a,b,f,tol)
GR = (sqrt(5)+1) / 2; % Golden Ratio Number
c = b - (b - a) / GR;
d = a + (b - a) / GR;
while abs(b - a) > tol
if f(c) < f(d) % f(c) > f(d) to find the maximum
b = d;
else
a = c;
end
% We recompute both c and d here to avoid loss of precision which may lead to incorrect results or infinite loop
c = b - (b - a) / GR;
d = a + (b - a) / GR;
end
x = (a+b)/2;
end
function y = f(x)
y = x.^2 - 6*x + 15;
end

请先登录,再进行评论。

类别

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

产品

Community Treasure Hunt

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

Start Hunting!

Translated by