Learn R Programming

comphy (version 1.0.5)

solveLS: Multilinear Least Squares

Description

Find the parameters, \(a_1,\dots,a_{m+1}\), of the linear model with \(m\) parameters, using the least squares technique on a group of \(n\) data points in the \(m\) dimensional Cartesian space.

Usage

solveLS(x, intercept = TRUE, tol = NULL)

Value

A vector of length \(m\) containing the \(m\)

numeric values of the estimated linear model parameters. The function also prints out the numerical value of the sum of squared residuals. If more than one solution is possible (infinite-solutions case) the function returns a NULL and prints out a related message.

Arguments

x

A \(n \times (m+1)\) matrix or data frame where the first \(m\) elements of each row contain the coordinates of a data point, and the last element contain the value corresponding to the linear model.

intercept

A logical variable. It indicates whether to omit or keep the constant \(a_{m+1}\) in the model. The default is intercept=TRUE as removing the constant is not advisable, unless there is an absolute certainty (for example in mechanistic models) that it has to be removed.

tol

A real number. The solution of a linear system can be compromised when the condition number of the matrix of coefficients is particularly high (ill-conditioned matrices). tol is the reciprocal of the condition number. For values of tol smaller than 1e-17, ill-conditioning is deemed to be sever enough not to guarantee an accurate solution. For such values the function stops execution, returning an error message. In fact, the solution can still be accurate, notwithstanding ill-conditioning, and the user can force the calculation of a solution using a value of tol smaller than 1e-17. Default is NULL, corresponding to a tol=1e-17.

Details

The linear model with \(m\) parameters has the following analytic form: $$ y = a_1x_1 + a_2x_2 + \dots + a_mx_m + a_{m+1} $$ The \(n\) data points are contained in a matrix or data frame with \(m+1\) columns and \(n\) rows. The first \(m\) elements of each row contain the coordinates of a data point; the last element contains the corresponding value of the linear fitting, \(y_i\). The least squares procedure is carried out as solution of a matrix equation, via the solve function.

Examples

Run this code
# 5 points exactly on y = 2x_1 - x_2 + 3
p1 <- c(0,1,2)
p2 <- c(1,0,5)
p3 <- c(1,1,4)
p4 <- c(0,2,1)
p5 <- c(2,0,7)

# Assemble points in a single matrix for input
x <- matrix(c(p1,p2,p3,p4,p5),ncol=3,byrow=TRUE)

# Find the least squares estimate of a_1,a_2,a_3
a <- solveLS(x)
print(a)

Run the code above in your browser using DataLab