I have a equation system and I want to solve it using numerical methods. I want to get a close solution given a starting seed. Let me explain.
I have a vector of constants ,X
, of values:
X <- (c(1,-2,3,4))
and a vector W
of weights:
W <- (c(0.25,0.25,0.25,0.25))
I want that the sum of the components of W will be (sum(W)=1
), and the sum of the multiplication of X
and W
element by element will be a given number N
(sum(W*X)=N
).
Is there a easy way to do this in R? I have it in Excel, using Solver, but I need to automatize it.
Here is your constant and your target value:
You need a function to minimize. The first line contains each of your conditions, and the second line provides a measure of how to combine the errors into a single score. You may want to change the second line. For example, you could make one error term be more heavily weighted than the other using
sum(c(1, 5) * errs ^ 2)
.The simplest thing is to start with all the weights the same value.
Use
optim
to optimize.The
par
element contains your weights.There is no unique solution for this problem. If you try other initial values for
w
you will most likely get different results fromoptim
.The problem can be formulated as solving an underdetermined system of linear equations.
We seek a solution that satisfies
A %*% w = b
but which one? Minimum norm solution? Or maybe some other one? There are infinitely many solutions. Solutions can be given using the pseudo-inverse of the matrixA
. Use packageMASS
for this.The minimum norm solution is
And check with
A %*% wmnorm - b
andfn(wmnorm)
. See the Wikipedia page System of linear equations the sectionMatrix solutions
.The solutions are given by
where
z
is an arbitrary vector ofncol(Az)
elements. And now generate some solutions and checkAnd you'll see that these two solutions are valid solutions when given as argument to
fn
. And are quite different from the solution found byoptim
. You could test this by choosing a different starting pointinit_w
for example byinit_w1 <- runif(4)/4
.