Am M
Am M

Reputation: 35

Evaluating a matrix with strings to get Eigenvalues

The main idea is that a user will input 3 strings to create a Hessian matrix, and the value of two or more variables, the goal is to calculate the eigenvalues to know if the matrix is positively define or not.

So far, I've tried replacing the string with an int or using the eval() function on the matrix, but it seems like it's not compatible with a matrices.

Here's an example of the code I have so far.

#Hessian
x = 0
y = 0
input_1 = '6x, -3, 0'
input_2 = '-3, 6y, 0'
input_3 = '0, 0, 0'
input_1 = input_1.replace('x', '*x')
input_2 = input_2.replace('y', '*y')
input_1 = input_1.split(',')
input_2 = input_2.split(',')
input_3 = input_3.split(',')

hess = np.matrix([input_1,input_2,input_3])
hess

Which outputs:

matrix([['6*x', ' -3', ' 0'],
        ['-3', ' 6*y', ' 0'],
        ['0', ' 0', ' 0']], dtype='<U4')

Now, the problem is that I can't find a way to replace the variables 'x' and 'y' with the values declared above because these are still strings.

If I could find a way to convert the values of the matrix to integers and replace the values then I would use something like eigenval = np.all(np.linalg.eigvals(hess)) to calculate the eigenvalues.

Any tips or recommendations on how to change the elements of the matrix would be highly appreciated.

Thank you in advance.

Upvotes: 0

Views: 197

Answers (2)

Taylor Reece
Taylor Reece

Reputation: 516

You could take advantage of python's eval function which evaluates the value of strings

For example, if your code reads:

x = 5
z = eval('10*x')

then z would be equal to 50.

You could then use the map function to map eval onto your lists of strings. If you replace your split lines with something like this:

input_1 = list(map(eval, input_1.split(',')))
input_2 = list(map(eval, input_2.split(',')))
input_3 = list(map(eval, input_3.split(',')))

then your values that contain x's and y's would instead contain whatever number the string evaluates to.

Upvotes: 0

Xero Smith
Xero Smith

Reputation: 2076

Write a function to parse the input strings to the required format.

def parse_input(instring, x, y):
    xs = []
    for i in instring.split(','):
        if 'x' in i and 'y' in i:
            xs.append(x * y * int(i.replace('x', '').replace(y, '')))
        elif 'x' in i:
            xs.append(x * int(i.replace('x', '')))
        elif 'y' in i:
            xs.append(y * int(i.replace('y', '')))
        else:
            xs.append(int(i))
    return xs

Sample run:

>>> input_1 = '6x, -3, 0'
>>> input_2 = '-3, 6y, 0'
>>> input_3 = '0, 0, 0'
>>> [parse_input(s, 0, 0) for s in (input_1, input_2, input_3)]
[[0, -3, 0], [-3, 0, 0], [0, 0, 0]]

Upvotes: 1

Related Questions