Hi,
Here are some points which should help troubleshoot and fix the 'gradientDescent' function:
- Correct Syntax: Ensure the function definition starts with 'function' instead of 'unction'.
- Remove Data Loading Inside the function: The 'gradientDescent' function should not load data from a file. Instead, 'x', 'y', and 'theta' should be passed as arguments. Load the data and initialize the variables outside the function.
- Compute Cost Function: Ensure to have a 'computeCost' function defined to calculate the cost for linear regression.
Given below is a modified version of the code implementing the above changes and also illustrating its usage:
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
J_history = zeros(num_iters, 1);
errors = predictions - y;
theta = theta - (alpha / m) * (X' * errors);
J_history(iter) = computeCost(X, y, theta);
function J = computeCost(X, y, theta)
sqErrors = (predictions - y).^2;
J = 1 / (2 * m) * sum(sqErrors);
data = load('ex1data1.txt');
[theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters);
fprintf('Theta found by gradient descent: ');
fprintf('%f %f \n', theta(1), theta(2));
The following image shows the result achieved upon using the above script on dummy data:
I hope this helps!