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