0

I need to evaluate eigenvalues of a matrix which contains variables (see simplified code below). The function "test" enters other functions later and in the end I want to evaluate the function over a grid.

So far I am doing it with np.vectorize and nested for loops (very slow) and want to increase the evaluation speed by using the numpy.meshgrid on the functions. However, the only thing I receive is the error message

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print(test(xx,yy))
  File "test.py", line 4, in test
    return np.linalg.eig(np.array([[1,x],[2,y]]))
ValueError: setting an array element with a sequence.

I read through the thread

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

but did not understand how I can apply the solutions presented there to my problem.

import numpy as np

def test(x,y):
    return np.linalg.eig(np.array([[1,x],[2,y]]))

xx,yy =np.meshgrid(np.linspace(0,1,5),np.linspace(0,1,5),sparse=True)

print(test(xx,yy))
  • 1
    Although it may be easy enough to identify the error in just a few lines of code, it's usually helpful to provide the full traceback of the exception rather than just the message. – glibdud Oct 14 '19 at 20:28
  • I edited the whole traceback into my post. – ricoschmidt_ber Oct 14 '19 at 20:37
  • `meshgrid` isn't a tool for speeding up calculations. It simply returns coordinate matrices from coordinate vectors. – Chris Mueller Oct 14 '19 at 20:55
  • @ChrisMueller ok but still it should be possible to also set up a grid and apply that function to that grid right? – ricoschmidt_ber Oct 15 '19 at 14:31
  • What exactly are you trying to achieve? np.linalg.eig needs to receive a square array. But xx and yy are of shape (1,5) since you created them sparse... – ec2604 Oct 21 '19 at 15:34

1 Answers1

0

Your problem is this line:

np.array([[1,x],[2,y]])

xx is already a matrix with shape (1,5), and yy has shape (5,1), and therefore the aforementioned line doesn't work.

It's not really clear how you want to concatenate these matrices, but assuming you somehow did, np.linalg.eig expects a square array.

If I could venture a guess, you want to create xx,yy with a dense meshgrid, and evaluate some function f(x,y) over the meshgrid - this'll give you a square array, which you can then use with np.linalg.eig

For example:

import numpy as np

def test(z):
   w,v = np.linalg.eig(z)
   return w #These are the eigenvalues

xx,yy = np.meshgrid(np.linspace(0, 1, 5), np.linspace(0, 1, 5), sparse=False)
z = np.sin(xx**2 + y**2)
print(test(z))
ec2604
  • 501
  • 3
  • 11