Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

How to write program run matrix as below in python?

Thanks for everyone's reply. I will explain here. Suppose there is a given matrix

    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]]

for example a feasible solution is [[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

I want to update x to make sure:

 (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]
       ...

How to program to find the feasible x?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

answer updated, i wrote some code to parse variables.

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'xdd')
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*)*(xdd)')
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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...