Expand vector in terms of others
I want to solve the equation:
v0 = a1*v1 + a2*v2 + a3*v3 + a4*v4 + a5*v5
where v0, v1, v2, v3, v4, v5
is the known matrix of columns (vectors), and a1, a2, a3, a4, a5
are the numbers to be calculated. I want to know if there is a function in numpy,sympy
or scipy
to calculate the equation directly or how can I solve the equation. Please give me a link or a written example.
source to share
Your equation is a system of equations where each element v0
is expressed as the sum of the corresponding elements in the arrays v1,v2,v3,v4,v5
.
This is a very specific case, i.e. the number of unknowns a1,a2,a3,s4,s5
is equal to the number of equations, which is the length of the vectors v1,v2,v3,v4,v5
.
from numpy import allclose,zeros_like
from numpy.random import rand
from numpy.linalg import solve
# generate the 5 vectors as random arrays
mat = rand(5,5)
v1,v2,v3,v4,v5 = mat.T
v0 = rand(5)
x= solve(mat,v0)
#first check
assert allclose(dot(mat,x),v0)
#2nd check, which is the equation of the OP
res = zeros_like(v0)
for xj,vj in zip([v1,v2,v3,v4,v5],x):
res+= xj*vj
assert allclose(res,v0)
source to share