benny
benny

Reputation: 133

Least square optimization in R

I am wondering how one could solve the following problem in R.

We have a v vector (of n elements) and a B matrix (of dimension m x n). E.g:

    > v 
    [1] 2 4 3 1 5 7

    > B
         [,1] [,2] [,3] [,4] [,5] [,6]
    [1,]    2    1   5    5    3    4
    [2,]    4    5   6    3    2    5
    [3,]    3    7   5    1    7    6

I am looking for the m-long vector u such that

    sum( ( v - ( u %*% B) )^2 )

is minimized (i.e. minimizes the sum of squares).

Upvotes: 2

Views: 1800

Answers (1)

josliber
josliber

Reputation: 44299

You are describing linear regression, which can be done with the lm function:

coefficients(lm(v~t(B)+0))
#      t(B)1      t(B)2      t(B)3 
#  0.2280676 -0.1505233  0.7431653 

Upvotes: 5

Related Questions