create a regression line of height and weight in matlab

To create a regression line of height and weight in Matlab, first, you need to import your data set into Matlab. Assuming your data is stored in two vectors, height and weight, you can use the plot function to visualize the data:

main.m
plot(weight, height, 'o');
xlabel('Weight');
ylabel('Height');
title('Height vs Weight');
90 chars
5 lines

This will create a scatter plot of the data points.

Next, you can use the polyfit function to calculate the coefficients of the regression line. Since we want a linear regression, we use a degree of 1:

main.m
p = polyfit(weight, height, 1);
32 chars
2 lines

The polyfit function returns the coefficients of the linear equation in the form of a vector. The first element is the slope and the second element is the y-intercept.

To plot the regression line on top of the scatter plot, you can use the polyval function:

main.m
x = min(weight):max(weight);
y = polyval(p, x);
hold on;
plot(x, y, 'r-');
75 chars
5 lines

This will plot the regression line in red on top of the scatter plot.

Putting it all together, the complete code for creating a regression line of height and weight in Matlab would look like this:

main.m
% Load data
load('height_weight_data.mat');

% Plot data
plot(weight, height, 'o');
xlabel('Weight');
ylabel('Height');
title('Height vs Weight');

% Calculate coefficients of regression line
p = polyfit(weight, height, 1);

% Plot regression line
x = min(weight):max(weight);
y = polyval(p, x);
hold on;
plot(x, y, 'r-');
323 chars
18 lines

Note that you will need to replace height_weight_data.mat with the name of your data file. Also, make sure that your data is stored as column vectors in Matlab.

gistlibby LogSnag