0

This is my first time asking something around here, so I hope I formulate the question in the best way possible.

I've been learning python for a couple of months now and I decided to put it to use for a problem I have to solve. It involves some deal of linear algebra, so I'll try to establish the maths first. Basically, suppose that you are given a vector in some basis (to be concise, I'll write everything in two dimensions) which we write as

v = (a*e_1 + b*e_2, c*e_1 + d*e_2)

which means that I can get v as the product of the vector (e_1,e_2) and a 2x2 matrix ((a,b),(c,d)). Now, my problem is the following: given the vector v, I want to extract the matrix ((a,b),(c,d)) and put it into a numpy array. Since eventually I will need to do this for a list of vectors, I would like to be able to give as input a list with entries in the form of strings which represents the vector, say:

vector = [2*e_1, -e_1 + e_2]

and get as output the matrix, as a numpy array, that projects "vector" onto the basis, that is

matrix = np.array([[2, 0], [-1, 2]])

is this possible? And, if so, can anyone point me in the right direction? I have been staring at the screen for a bit and haven't figured out how to do it, so any kind of hint would be very much appreciated.

EDIT:

So, thanks to everyone that has answered so far. Let me expand upon the problem I have and what I want to do with it.

I have, as input, a set of vectors whose components are all linear combinations of a set of basis vectors (k1,k2,...,kn) with coefficients in the set (+1,-1,0). This set of vectors is of size N, where in general, N >= n. Then, given a choice of n vectors out of the N input vectors, I can regards those n vectors, which I'll call (k1',k2',...,kn') as a new basis and compute the matrix which transforms from the basis (k1,k2,...,kn) to the new basis (k1',k2',...,kn'). Moreover, I can do this with a second choice of another n vectors and get the transformation matrix to a third basis (k1'',k2'',...,kn'').

What my problem really needs is for me to find the matrix that transforms from the basis b1 = (k1',k2',...,kn') to the basis b2 = (k1'',k2'',...,kn''), given that the input is written in the basis b = (k1,k2,...,kn). However, I know that if I write b1 = Ab and b2 = Bb for some matrices A and B, I can find the matrix C in the relation b1 = Cb2 by finding the inverse for B and writting C=A*B^{-1}. After posting this question and playing with stuff, I came up with the following code:

    import numpy as np
    import itertools

    input_vectors = [['+l1', '+l2'], ['+l1+l2', '+l1']]
    dim = len(input_vectors)
    matrix_list = [np.zeros((dim, dim)) for i in input_vectors]

    for element in zip(input_vectors, matrix_list):
        momenta = element[0]
        matrix = element[1]
        if '+l1' in momenta[0]:
            matrix[0][0] = 1
        if '+l2' in momenta[0]:
            matrix[0][1] = 1
        if '-l1' in momenta[0]:
            matrix[0][0] = -1
        if '-l2' in momenta[0]:
            matrix[0][1] = -1

        if '+l1' in momenta[1]:
            matrix[1][0] = 1
        if '+l2' in momenta[1]:
            matrix[1][1] = 1
        if '-l1' in momenta[1]:
            matrix[1][0] = -1
        if '-l2' in momenta[1]:
            matrix[1][1] = -1

which actually yields my desired output. However, it looks awfully redundant and evidently not easy to generalize.

3
  • How are you currently representing vector = [2*e_1, -e_1 + e_2] in python? What are the data types of e_1 and e_2? Commented Apr 15, 2021 at 20:03
  • Currently, I'm thinking of representing e_1 and e_2 as strings (the actual coefficients of e_1 and e_2 in the problem are always going to equal 1, -1 or 0, but I need something that makes a distinction between e_1 and e_2). However, I don't even know if that is the best approach. Commented Apr 15, 2021 at 20:15
  • Wow, I just got confused with your example np.array([[2, 0], [-1, 2]]), is it really 2 in the last position? Is your matrix transposed? Commented Apr 15, 2021 at 20:23

1 Answer 1

1

What are you trying to do with this linear algebra? So you want to have this [2*e_1, -e_1 + e_2] as input and this np.array([[2, 0], [-1, 2]]) as output?

Parsing the string is just too painful, so let's supposed you just wrote that expression in Python (if not use exec):

string_expression = "[2*e_1, -e_1 + e_2]" # If you read strings from file or input
e_1 = np.array([1, 0]) # Those vectors need to be defined before eval
e_2 = np.array([0, 1])
python_expression = eval(string_expression) # You don't need this if you just write the python expression yourself, like so
# python_expression = [2*e_1, -e_1 + e_2] # This is simpler
matrix = np.array(python_expression)

If you want a more generic approach:

def get_matrix(string_expression, dims, vector_name='e'):
     for i in range(dims):
          base = np.zeros(dims)
          base[i] = 1 # It just a vector in the form [0, 0, ... ,1, ... 0, 0]
          base_name = '%s_%d' % (vector_name, i+1) # string for e_i
          locals()[base_name] = base # create a local variable named e_i
     expression = eval(string_expression) # evaluates the string as Python code
     return np.array(expression) # Create a matrix from the list of arrays

get_matrix('[2*e_1, -e_1 + e_2]', 2, 'e') # returns np.array([[2, 0], [-1, 1]])
get_matrix('[l_1+l2, l_1]', 2, 'l') # returns np.array([[1, 1], [1, 0]])
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot for your answer! I just made an edit to the original question, which hopefully helps making my problem and the motivation for it clearer. I have one question, though: what does the .T in matrix = np.array(python_expression).T do? I have only done vary basic stuff with numpy so I don't know a lot about the syntax and methods
It is to transpose the matrix, .T is a short for np.transpose. Doesn't this answer work? I have also made a generic function, it accepts any python expression. You should know that the identity values for the vectors (one-hot encoding) are what creates the matrix.
Hi! Thanks for the answer! I just came back to this, and it definitely does the job. I didn't completely understand the logic before, so I was curious about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.