Clear Filters
Clear Filters

Population and profit using linear regression

2 views (last 30 days)
Suppose there are 97 data sets .I have to compute the cost using linear regression .I am calling the data from a txt. file .
function J = computeCost(X, y, theta)
J=0;m = length(y);
data=load('ex1data1.txt');
x=data(:,1);y=data(:,2);
h=X*theta;
error=h-y;
error_sqr=(h-y).^2;
J=(1/(2*m))*(sum(error_sqr));
If I use the following code in command window then the following results is shown.What is the problem with the code ?
computeCost(ones(m, 1), data(:,1),data(:,2),zeros(2, 1))
Undefined function or variable 'm'.

Accepted Answer

Star Strider
Star Strider on 8 Sep 2015
This line is in your main (or calling) script, and you likely have not yet defined ‘m’ in it so that ‘m’ is a variable in the main script workspace:
computeCost(ones(m, 1), data(:,1),data(:,2),zeros(2, 1))
If ‘m’ is first defined in the function, it is local to that function, not to the main script workspace.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!