How to write program run matrix as below in python?
Question: 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?


Answer: 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'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]
    

