Im trying to use gradient decent with a for loop to determine the value of x that minimizes the function

조회 수: 2 (최근 30일)
Im trying to use gradient descent to numerically determine the value of x that
minimizes the function f(x) = x^2 − 3x + 1 with its derivative f(x) = 2x − 3.
Starting from x(0) = 0, im trying to plot the value of the
function f(x) as a function of the number of iterations for a few different
values of α.
This is my current code:
clc, clearvars, close all
iterations = 10;
alpha = 0.15;
x = zeros(iterations,1);
x(1) = -1;
for k = 2:iterations
x(k) = x(k-1) - alpha*( 2*x(k)-3 )
end
figure(1)
plot(k,x)
figure(2)
plot(x1,f_x)
Im not sure how to plot this, after its calculated i could use f= x.^2-3*x+1 to calculate its function value.
Any ideas how i could make it work?

답변 (2개)

David Hill
David Hill 2022년 11월 22일
iterations = 10;
alpha = 0.15;
x = zeros(iterations,1);
x(1) = -1;
for k = 2:iterations
x(k) = (x(k-1)+alpha*3)/(1+2*alpha);
end
plot(x)

Torsten
Torsten 2022년 11월 22일
편집: Torsten 2022년 11월 22일
f = @(x) x.^2 - 3*x + 1;
iterations = 15;
alpha = 0.15;
x = zeros(iterations,1);
x(1) = 0;
for k = 2:iterations
x(k) = x(k-1) - alpha*( 2*x(k-1)-3 ) ;
end
figure(1)
hold on
plot(x,f(x),'o')
xplot = linspace(0,2,100);
yplot = f(xplot);
plot(xplot,f(xplot))
hold off
grid on
figure(2)
plot(1:iterations,x,'o')
grid on

카테고리

Help CenterFile Exchange에서 Title에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by