I am having trouble while joining a matrix and a vector togheter in Python.
Basically, assume I am given a matrix A such that
A = [
[1,2,3,1,0],
[3,2,2,0,1],
]
And a bunch of indexes such that
unboundedVarsIndex = [3]
My first task would be to go into index 2 of matrix A, and add a extra column in the matrix such that A[i 1] = -1 * A[i]. I was able to do this with the following code:
B = np.array(A).T
newA = [[]] * (len(B) len(unboundedVarsIndex))
for i in range(len(newA)-1):
for indexVal in unboundedVarsIndex:
if i == indexVal-1:
newA[i 1] = -1*B[i]
if len(newA[i]) == 0:
newA[i] = B[i]
else:
newA[i 1] = B[i]
boolean = True
k = len(newA)-1
for indexVal in unboundedVarsIndex:
if k == indexVal:
boolean = False
newnewA = [[]] * (len(newA) 1)
newnewA[len(newnewA-1)] = -1*newA[len(newA)-1]
for i in range(len(newA)):
newnewA[i] = newA[i]
if(boolean):
A = np.array(newA).T
else:
A = np.array(newnewA).T
With this code, I get the following output:
A = [
[1,2,3,-3,1,0]
[3,2,2,-2,0,1]
]
Which is also what I wanted. My first problem is: this code doesn't work If I have more than one unbounbdedVarIndex. If I use, for example,
unboundedVarsIndex = [2,3]
The code gives me the following error:
newA[i 1] = B[i]
IndexError: index 5 is out of bounds for axis 0 with size 5
How would one fix this issue?
Thanks for any help in advance.
CodePudding user response:
This code does what you want:
A = [
[1,2,3,1,0],
[3,2,2,0,1],
]
unboundedVarsIndex = [2, 3]
unboundedVarsIndex.sort(reverse=True)
for index in unboundedVarsIndex:
for each in A:
each.insert(index, - each[index - 1])
print(unboundedVarsIndex)
print(A)
