感谢大家的回复。我会在这里解释一下。 假设有一个给定的矩阵
x y B = [5,-4,5,-6]
[[0,0,0,0], [[0,1,0,1],
[0,0,0,0], [0,0,0,0],
[0,0,0,0], [0,0,0,1],
[0,0,0,0]] [0,0,0,0]]
例如可行的解决方案是[[0,4,0,1],[0,0,0,0],[0,0,0,5],[0,0,0,0]] 4 + 1-0 == 5 0-4 == -4 5-0 == 5 0 - 5-1 == -6
我想更新x以确保:
(1) if y[i][j] == 0:
x[i][j] = 0
(2) x[0][0]+x[0][1]+x[0][2]+x[0][3]-x[0][0]-x[1][0]-x[2][0]-x[3][0] = B[0]
x[1][0]+x[1][1]+x[1][2]+x[1][3]-x[0][1]-x[1][1]-x[2][1]-x[3][1] = B[1]
...
如何编程找到可行的x?
答案 0 :(得分:0)
回答更新,我写了一些代码来解析变量。
B = [5,-4,5,-6]
y = [
[0,1,0,1],
[0,0,0,0],
[0,0,0,1],
[0,0,0,0],
]
x = []
for i, row in enumerate(y):
temp = []
for j, col in enumerate(row):
if col != 0:
temp.append(str(col) + '*x' + str(i) + str(j))
else:
temp.append(col)
x.append(temp)
#for one in x:
# print one
equ = []
for i in xrange(4):
temp1 = []
temp2 = []
for j in xrange(4):
temp1.append(x[i][j])
temp2.append(x[j][i])
temp2.append(B[i])
equ.append(tuple(temp1 + temp2))
equtions = []
for one in equ:
s = '%s + %s + %s + %s - %s - %s - %s - %s = %s' % one
equtions.append(s)
for one in equtions:
print one
import re
from copy import deepcopy
equ_bak = deepcopy(equtions)
p_var = re.compile(r'x\d\d')
vars = set([])
for one in equ_bak:
m = p_var.findall(one)
vars |= set(m)
vars = sorted(list(vars))
p_ef = re.compile(r'([+-]* *\d*)\*(x\d\d)')
effs = []
for one in equ_bak:
m = p_ef.findall(one)
#print m
temp = [0] * len(vars)
for num, var in m:
try:
temp[vars.index(var)] = float(num.replace(' ', ''))
except:
pass
effs.append(tuple(temp))
#for one in effs:
# print one
import numpy as np
A = np.array(effs)
x = np.linalg.lstsq(A,B)
print vars
print x[0]