How to express multiple linear regression graphically in MATLAB?

Viewed 67

I am trying to generate the same plot as the one shown below,

enter image description here

, and I have written the following piece of code in MATLAB,

x1 = [0, 0, 1, 1];
x2 = [0, 1, 0, 1];
Y = [4, 3, 2, 4];
plot3(x1,x2,Y,'o','Color','r','MarkerSize',10, 'MarkerFaceColor', 'r')
hold on
[x y] = meshgrid(0:0.1:2, 0:0.1:2);
z = 1.25 + 2.5 * x + 1.5 * y;
surf(x, y, z,'FaceAlpha',0.5)
xlabel('x1');ylabel('x2');zlabel('y');
hold off
grid on

Would you please tell me how I can plot a line that connects the data point with its corresponding value of the generated surface for the same plot I generated with MATLAB.

Many thanks for your time.

1 Answers

I added a loop within the "hold" portion of your code.

x1 = [0, 0, 1, 1];
x2 = [0, 1, 0, 1];
Y = [4, 3, 2, 4];
plot3(x1,x2,Y,'o','Color','r','MarkerSize',10, 'MarkerFaceColor', 'r')
hold on
[x y] = meshgrid(0:0.1:2, 0:0.1:2);
z = 1.25 + 2.5 * x + 1.5 * y;
surf(x, y, z,'FaceAlpha',0.5)
xlabel('x1');ylabel('x2');zlabel('y');
for ii=1:numel(Y)
    plot3( [x1(ii),x1(ii)], [x2(ii),x2(ii)], [Y(ii),1.25+2.5*x1(ii)+1.5*x2(ii)] );
end
hold off
grid on

Also, currently your surface z is hard-coded, therefore the code for the vertical line is hard-coded as well. But once you estimate your parameters for the regression, you could just as easily dynamically adjust the surface and the vertical lines.

Related