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

조회 수: 2 (최근 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에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by