Reputation: 21
I have the following problem. I want to evaluate the following function
def sigLinZ(self,val,omega):
A = 1
C = 0
D = 1
B =1./(omega*val*1j)
return np.asmatrix(np.array([[A,B],[C,D]]))
in such a way that I can use it in pyplot in such a way:
omega = numpy.arange(0,100,1)
y = classInstance.sigLinZ(12,omega)
plt.plot(omega,y)
but this does not work. Python says:
Traceback (most recent call last):
File "testImpedanz.py", line 132, in test6_lineImpedanz
print "neue Matrix: ", lineImpe.sigLinZ('C',lineImpe.C(),np.array([600e6,300e6]))
File "/afs/physnet.uni-hamburg.de/users/ap_h/pgwozdz/Dokumente/PythonSkriptsPHD/ImpedanzCalculation.py", line 350, in sigLinZ
return np.mat(np.array([[A,B],[C,D]]))
TypeError: only length-1 arrays can be converted to Python scalars
I know for numpy functions this procedure works just fine but for my function it does not work at all.
Upvotes: 2
Views: 932
Reputation: 88248
First, the problem has nothing to do with pylab and is only numpy related. It fails on the line:
return np.asmatrix(np.array([[A,B],[C,D]]))
And actually fails here
np.array([[A,B],[C,D]])
The reason why it doesn't work can be determined from the error message and the shape of the objects. When you pass omega
with a shape of
print omega
>>> (100,)
and try to put it into an object of size 2x2
, [[A,B],[C,D]]
it will indeed complain about
TypeError: only length-1 arrays can be converted to Python scalars
Did you intend to return a scalar value from the function sigLinZ
? I'm inferring that since you are trying to do a simple plt.plot
command with the result.
Edit: If you really want a matrix of matrices, you need to make the other entries the same size as B
def sigLinZ(val,omega):
B = 1./(omega*val*1j)
A = 1*np.ones(B.shape)
C = 0*np.ones(B.shape)
D = 1*np.ones(B.shape)
return np.array([[A,B],[C,D]])
Which gives a shape of (2,2,100)
, i.e. the last index sets the array count of a bunch of 2x2 matrices. Sidenote, as it stands, B
divides by zero.
Upvotes: 1
Reputation: 68742
You are attempting to insert an array into the element of matrix in your definition of omega
that you're passing into the method. Either you need to iterate over omega
passing each element to sigLinZ
separately, or you need to re-write sigLinZ
to handle the array and return something like a list of matrices or 3D array.
Upvotes: 3