In [49]:
clear; close all; clc

In [50]:
% Loading given data
data = load('./data/ex1data1.txt');
X = data(:, 1); 
y = data(:, 2);
m = length(y);

In [51]:
% Plotting data to see our data
fprintf('Plotting Data ... \n');
hold on;
plotData(X, y);


Plotting Data ... 
Gnuplot Produced by GNUPLOT 5.0 patchlevel 5 -5 0 5 10 15 20 25 5 10 15 20 25 Revenue Population gnuplot_plot_1a

In [52]:
fprintf('Running Gradient Descent ...\n')
% Add a column of ones to X
X = [ones(m,1), data(:,1)];
% Initialize fitting parameters
theta = zeros(2,1);


Running Gradient Descent ...

In [53]:
% Set gradient descent parameters
% learning rate:
alpha = 0.01;
iterations = 1500;

In [54]:
% compute and display initial cost
computeCost(X, y, theta);

In [55]:
% Run gradient descent
theta = gradientDescent(X, y, theta, alpha, iterations);


 4.4834

In [56]:
% print theta to screen
fprintf('Theta found by gradient descent: ');
fprintf('%f %f \n', theta(1), theta(2));


Theta found by gradient descent: 
-3.630291 1.166362 
Theta found by gradient descent: 

In [57]:
% Plotting the linear fit
plot(X(:,2), X*theta, '-')
legend('Training data', 'Linear regression')
hold off; % Don't overlay any more plots on this figure


warning: legend: ignoring extra labels
warning: called from
    legend at line 428 column 9
Gnuplot Produced by GNUPLOT 5.0 patchlevel 5 0 5 10 15 20 25 5 10 15 20 25 Training data Training data

In [ ]: