user3600497
user3600497

Reputation: 1661

How can I plot this?

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

enter image description here

how do I plot

enter image description here

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

Answers (1)

Raab70
Raab70

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:

Paraboloid Output

Upvotes: 1

Related Questions