Skip to content

Instantly share code, notes, and snippets.

@anuvrat
Created May 26, 2012 22:56
Show Gist options
  • Save anuvrat/2795554 to your computer and use it in GitHub Desktop.
Save anuvrat/2795554 to your computer and use it in GitHub Desktop.
Compute cost for linear regression
function J = computeCost(X, y, theta)
%COMPUTECOST Compute cost for linear regression
% J = COMPUTECOST(X, y, theta) computes the cost of using theta as the
% parameter for linear regression to fit the data points in X and y
% Initialize some useful values
m = length(y); % number of training examples
% We need to return the following variable
J = sum((X * theta - y) .^ 2) / (2*m)
end
Copy link

ghost commented Jun 5, 2021

Guys, you just have to run the ex1.m file.
Otherwise, it will throw an error.
\

@jackinhub
Copy link

jackinhub commented Jun 24, 2021

Hi Guys,
Here is my solution.

function J = computeCost(X, y, theta)
%COMPUTECOST Compute cost for linear regression
% J = COMPUTECOST(X, y, theta) computes the cost of using theta as the
% parameter for linear regression to fit the data points in X and y
data = load('ex1data1.txt'); % read comma separated data

% Initialize some useful values
m = length(data); % number of training examples
X = [ones(m,1),data(:,1)]; y = data(:, 2);
theta = zeros(2,1);
% You need to return the following variables correctly
%J = 0;

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta
% You should set J to the cost.

J = sum((Xtheta - y).^2)/(2m);

% =========================================================================

end

@Abhishek-michael
Copy link

you have to add the asterixs in the formula otherwise it will throw an error

@rohan5901
Copy link

what is the answer of J as I am getting incorrect answer while submitting

Copy link

ghost commented Aug 3, 2021

First write your code in computeCost.m don't run this code
then run ex.m and submit the assignment

@AswinAzikar
Copy link

data = load('ex1data1.txt'); % read comma separated data
y = data(:, 2);
m = length(y); % number of training examples
X = [ones(m, 1), data(:,1)]; % Add a column of ones to x
theta = zeros(2, 1);
excellent

@aravindhanchandran
Copy link

code is worked

@mojito-1
Copy link

thanks a lot bros

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment