multivariate linear least-squares fitting in matlab

In MATLAB, you can use the polyfitn function from the Curve Fitting Toolbox to perform multivariate linear least-squares fitting.

Here's an example:

main.m
% generate some sample data
x1 = rand(100,1);
x2 = rand(100,1);
y = 2*x1 + 3*x2 + randn(100,1);

% define the independent variables
X = [x1,x2];

% perform linear least-squares fitting
p = polyfitn(X, y, 1);
208 chars
11 lines

In this example, polyfitn fits a linear model of the form y = p(1)*x1 + p(2)*x2 + p(3) to the data.

You can then use the p coefficients to predict the response variable y for new values of x1 and x2:

main.m
% generate some new x values to predict with
x1_new = rand(10,1);
x2_new = rand(10,1);

% predict the response variable
y_pred = polyvaln(p, [x1_new, x2_new]);
160 chars
7 lines

Note that polyfitn can handle higher-order polynomial models and also allows you to specify constraints on the coefficients. See the MATLAB documentation for more information.

related categories

gistlibby LogSnag