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

2 views (last 30 days)
Edward Ekman on 22 Nov 2022
Edited: Torsten on 22 Nov 2022
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?

David Hill on 22 Nov 2022
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 on 22 Nov 2022
Edited: Torsten on 22 Nov 2022
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