[R] least squares solution to linear system
Berend Hasselman
bhh at xs4all.nl
Sat Feb 4 19:56:38 CET 2012
On 04-02-2012, at 19:14, Alaios wrote:
> Dear all
> I am having a linear system of the form
> A*X=B and I want to find the X by using least squares.
> For example my A is of dimension [205,3] and my B is of dimension[205,1]
>
> I am looking for the X matrix which is of the size [3,1]. In the matlab I was doing that by the function
>
>
> X = LSCOV(A,B) returns the ordinary least squares solution to the
> linear system of equations A*X = B, i.e., X is the N-by-1 vector that
> minimizes the sum of squared errors (B - A*X)'*(B - A*X), where A is
> M-by-N, and B is M-by-1
>
>
> for example for the matrices
>
> A =
>
> 1 2 3
> 4 5 6
> 7 8 9
>
> K>> B=[1 2 3]
>
> B =
>
> 1 2 3
>
>
>>> lscov(A,B')
>
> ans =
>
> -0.0000
> 0
> 0.3333
>
> How I can get the same in R? I know about the lm function but it looks complicated to me how to insert formula and how to get exactly back only what I need
?qr
Example:
A <- matrix(runif(15),5)
b <- 1:5
solve(qr(A, LAPACK=TRUE), b)
or
lm(b ~ 0 + A)
Berend
More information about the R-help
mailing list