Reputation: 1661
Doing a little machine learning, and working on some linear regression. I can't seem to plot this in Matlab.
Given a bunch of data
how do I plot
in matlab? I know it should be parabolic, but my code (shown below) doesn't give me a paraboloid
.
x=linspace(0,1,1001);
M=numel(x);
y=2*x-3+(-2+4*rand());
plot(x,y)
[theta1,theta2]=meshgrid(0:0.01:3,-5:0.01:-2);
J=zeros(length(theta1),length(theta2));
for i = 1:M
J=J+(theta1*x(i)-theta2-y(i)).^2;
end
J=(2*M)^(-1)*J;
mesh(theta1,theta2,J)
Upvotes: 0
Views: 70
Reputation: 721
There are two very minor problems with your code:
Number 1: Within the sum it should be theta2*y(i)
.
Number 2: Your range is too small to see the paraboloid shape! Try running the example below:
x=linspace(0,1,1001);
M=numel(x);
y=2*x-3+(-2+4*rand());
plot(x,y)
[theta1,theta2]=meshgrid(-20:1:20,-20:1:20);
J=zeros(size(theta1));
for i = 1:M
J=J+(theta1*x(i)-theta2*y(i)).^2;
end
J=(2*M)^(-1)*J;
figure(1);
mesh(theta1,theta2,J)
xlabel('\theta_1');
ylabel('\theta_2');
Which produces:
Upvotes: 1