- Define the function.
- Compute the gradient of the function. You can implement this manually or utilize gradient MATLAB function.
- Implement the gradient descent algorithm.
- Finally, you can plot the gradients.
How to plot a function using gradient descent method?
70 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/820455/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/820460/image.png)
0 Kommentare
Antworten (1)
Ayush Aniket
am 24 Jan. 2025 um 11:38
To plot function and iterative value of the variables in MATLAB using gradient descent, you need to:
Refer to the example below:
% 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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!