How to plot a function using gradient descent method?

22 views (last 30 days)
-

Answers (1)

Prateekshya
Prateekshya on 4 Oct 2024
Hello Bijoya,
To plot functions in MATLAB using gradient descent, you need to follow a few steps. Gradient descent is an optimization algorithm used to find the minimum of a function. Here is a sample code of using gradient descent to find and plot the minimum of a quadratic function.
  • Define the Function: Choose a function to minimize. For simplicity, let's use a quadratic function .
  • Compute the Gradient: The gradient of is .
  • Implement Gradient Descent: Write a loop to iteratively update x using the gradient.
  • Plot the Function and the Descent Path: Plot the function and the points visited by the gradient descent algorithm.
% Define the function and its gradient
f = @(x) x.^2;
grad_f = @(x) 2*x;
% Gradient descent parameters
alpha = 0.1; % Learning rate
x0 = 10; % Initial guess
max_iter = 100; % Maximum number of iterations
tolerance = 1e-6; % Tolerance for stopping criterion
% Initialize variables
x = x0;
x_history = x; % To store the path
% Gradient descent loop
for iter = 1:max_iter
% Compute the gradient
grad = grad_f(x);
% Update the variable
x = x - alpha * grad;
% Store the history
x_history = [x_history, x];
% Check for convergence
if abs(grad) < tolerance
fprintf('Converged in %d iterations\n', iter);
break;
end
end
% Plot the function
x_plot = linspace(-10, 10, 100);
y_plot = f(x_plot);
figure;
plot(x_plot, y_plot, 'b-', 'LineWidth', 2);
hold on;
% Plot the descent path
y_history = f(x_history);
plot(x_history, y_history, 'ro-', 'MarkerFaceColor', 'r');
title('Gradient Descent on f(x) = x^2');
xlabel('x');
ylabel('f(x)');
legend('Function', 'Descent Path');
grid on;
You can use this example and modify it according to your equation.
I hope this helps!

Community Treasure Hunt

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

Start Hunting!