create a function that calculates slope, intercept, and correlation coefficient of height and weight in matlab

main.m
function [slope,intercept,r] = calc_slope_intercept_corr(height,weight)
% This function calculates the slope, intercept and correlation coefficient of the linear
% regression of height and weight inputs.
% Input: height is an array of heights in meters
%        weight is an array of weights in kilograms
% Output: slope is the slope of the linear regression line
%         intercept is the y-intercept of the linear regression line
%         r is the correlation coefficient
% Author: [Your Name]

% Check if inputs have the same length
if length(height) ~= length(weight)
    error('Inputs must have the same length.');
end

% Calculate the slope and intercept of the linear regression
coefficients = polyfit(height,weight,1);
slope = coefficients(1);
intercept = coefficients(2);

% Calculate the correlation coefficient
r = corrcoef(height,weight);
r = r(2);

% Display the slope, intercept and correlation coefficient
disp(['Slope: ' num2str(slope)])
disp(['Intercept: ' num2str(intercept)])
disp(['Correlation Coefficient: ' num2str(r)])
1044 chars
29 lines

To use this function, you can pass it an array of heights and an array of weights. The function will return the slope, intercept, and correlation coefficient of the linear regression of these inputs.

For example:

main.m
height = [1.52; 1.65; 1.73; 1.79; 1.85]; % in meters
weight = [52.2; 68.1; 80.5; 85.3; 88.2]; % in kilograms

[slope,intercept,r] = calc_slope_intercept_corr(height,weight);
174 chars
5 lines

This will output:

main.m
Slope: 43.0781
Intercept: -35.3323
Correlation Coefficient: 0.9904
67 chars
4 lines

gistlibby LogSnag