python ValueError: need more than 0 values to unpack - python

I tried to print out the left eigenvectors of a given matrix A6. AFunction take a integer n and a list L (of length n), and return a n by n matrix generated by entries in list L.
I want to see the left eigenvectors of a 6*6 matrix. I got ValueError: need more than 0 values to unpack which is caused by the printing line. Where is wrong??
A6 = AFunction(6,[1,2,3,4,5,6])
print('Av=cv eigenvectors are',A6.eigenvectors_left())
---update:---
For some reason the code started working... I didn't do anything specifically other than printing out the matrix first. :)

Related

Coding an iterated sum of sums in python

For alpha and k fixed integers with i < k also fixed, I am trying to encode a sum of the form
where all the x and y variables are known beforehand. (this is essentially the alpha coordinate of a big iterated matrix-vector multiplication)
For a normal sum varying over one index I usually create a 1d array A and set A[i] equal to the i indexed entry of the sum then use sum(A), but in the above instance the entries of the innermost sum depend on the indices in the previous sum, which in turn depend on the indices in the sum before that, all the way back out to the first sum which prevents me using this tact in a straightforward manner.
I tried making a 2D array B of appropriate length and width and setting the 0 row to be the entries in the innermost sum, then the 1 row as the entries in the next sum times sum(np.transpose(B),0) and so on, but the value of the first sum (of row 0) needs to vary with each entry in row 1 since that sum still has indices dependent on our position in row 1, so on and so forth all the way up to sum k-i.
A sum which allows for a 'variable' filled in by each position of the array it's summing through would thusly do the trick, but I can't find anything along these lines in numpy and my attempts to hack one together have thus far failed -- my intuition says there is a solution that involves summing along the axes of a k-i dimensional array, but I haven't been able to make this precise yet. Any assistance is greatly appreciated.
One simple attempt to hard-code something like this would be:
for j0 in range(0,n0):
for j1 in range(0,n1):
....
Edit: (a vectorized version)
You could do something like this: (I didn't test it)
temp = np.ones(n[k-i])
for j in range(0,k-i):
temp = x[:n[k-i-1-j],:n[k-i-j]].T#(y[:n[k-i-j]]*temp)
result = x[alpha,:n[0]]#(y[:n[0]]*temp)
The basic idea is that you try to press it into a matrix-vector form. (note that this is python3 syntax)
Edit: You should note that you need to change the "k-1" to where the innermost sum is (I just did it for all sums up to index k-i)
This is 95% identical to #sehigle's answer, but includes a generic N vector:
def nested_sum(XX, Y, N, alpha):
intermediate = np.ones(N[-1], dtype=XX.dtype)
for n1, n2 in zip(N[-2::-1], N[:0:-1]):
intermediate = np.sum(XX[:n1, :n2] * Y[:n2] * intermediate, axis=1)
return np.sum(XX[alpha, :N[0]] * Y[:N[0]] * intermediate)
Similarly, I have no knowledge of the expression, so I'm not sure how to build appropriate tests. But it runs :\

element wise matrix multiplication python

Hi I'm stuck on what on the face of it seems a simple problem, so I must be missing something!
I have a list (of indeterminate length) of matrices calculated from user values. - ttranspose
I also have another single matrix, Qbar which I would like to multiply (matrix form) each of the matrices in ttranspose, and output a list of the resultant matrices. << Which should be the same length as ttranspose.
def Q_by_transpose(ttranspose, Qmatrix):
Q_by_transpose = []
for matrix in ttranspose:
Q_by_transpose_ind = np.matmul(ttranspose, Qmatrix)
Q_by_transpose.append(Q_by_transpose_ind)
return (Q_by_transpose)
Instead when I test this with a list of 6 matrices (ttranspose) I get the a long list of mtrices, which appears to be in 6 arrays (as expected) but each array is made up of 6 matrices?
Im hoping to create a list of matrices for which I would then perform elementwise multiplication between this and another list. So solving this will help on both fronts!
Any help would be greatly appreciated!
I am new to Python and Numpy so am hopeful you guys will be able to help!
Thanks
It appears that instead of passing a single matrix to the np.matmul function, you are passing the entire list of matrices. Instead of
for matrix in ttranspose:
Q_by_transpose_ind = np.matmul(ttranspose, Qmatrix)
Q_by_transpose.append(Q_by_transpose_ind)
do this:
for matrix in ttranspose:
Q_by_transpose_ind = np.matmul(matrix, Qmatrix)
Q_by_transpose.append(Q_by_transpose_ind)
This will only pass one matrix to np.matmul instead of the whole list. Essentially what you're doing right now is multiplying the entire list of matrices n times, where n is the number of matrices in ttranspose.

How can i make an empty matrix that ican fill it out later by floats and strings

I want to make a matrix that at the first of program, i can't understand how many rows it has and during the program i will add each row to the matrix by using "vstack".
Each row of these matrix consist of 100 elements,some strings and some floats.
Y=[]
and later during the program i will make a new row in y array and i want to add it to Y.
Y=numpy.vstack([Y,y])
The error:
return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
ValueError: all the input array dimensions except for the concatenation axis must match exactly
I know that for using "vstack" I need to have "Y" with the same dimension s as y but here I don't know how can i define that.
I tried this way too:
Y=[]
And later by using h starting from 0 Y[h]=y
Error: IndexError: list assignment index out of range

Python Error: Setting an array element with a sequence

I am new to python, so please, bear with me!
This function:
def kerf(X,m):
[n_samples, ]= X.shape
n_sa, n_fe = m.shape
ker = np.zeros((n_samples, n_sa))
for i, x_i in enumerate(X):
for j, m_j in enumerate(m):
ker[i, j] = (np.dot(x_i, m_j)) # problem is here!!
return ker
I call it like this:
Z=kerf(myarray[0,[0,1]],myarray[:,[0,1]])
ker[i, j] = (np.dot(x_i, m_j))
ValueError: setting an array element with a sequence.
myarray is basically the same matrix. Why?
When I replace the problem line with:
print(np.dot(x_i, m_j).shape)
it repeatedly prints (2,).
ker[i, j] takes 1 value; 2 values is sequence.
Please give us the dimensions of the arrays at various points, such as myarray (I guessed and tried a (3,4)), and at the problem point. print(...shape) is an essential debugging tool in numpy.
Do you need help on figure out why it's (2,)? May I suggest stepping through the loop in an interactive shell, looking at shapes at various points along the way.
the 2 inputs to the dot look like:
(1.0, array([ 1., 1.]))
a scalar, and a 2 element array - so the dot is also a 2 element array.
You need to explain what size you expect these 2 arrays to be, and what size you expect the dot. Actually we can get the result - it's got to be (1,) or a scalar - 1 value to put in the one slot ker.
You can probably replace the double iteration with a single dot product (or if need be with an einsum call). But let's get this iteration working first.

Python how to assign values to a certain row of a matrix?

In Python,
I created a 10 x 20 zero-matrix, called X:
X = numpy.zeros((10, 20))
I have another 50 x 20 matrix called A.
I want to let the 4th row of matrix X take the value of the 47th row of matrix A.
How can I write this in Python?
Note: if X is a list, then I could just write X.append () However, here X is not a list...then how can I do this?
Or, if I just have a list that contains 20 numbers, how can I let the 4th row of matrix X equal to that list of 20 numbers?
Thank you!
I'll try to answer this. So the correct syntax for selecting an entire row in numpy is
M[row_number, :]
The : part just selects the entire row in a shorthand way.
There is also a possibility of letting it go from some index to the end by using m:, where m is some known index.
If you want to go between to known indices, then we will use
M[row_number, m:n]
where m < n.
You can equate the rows/columns of a 2D-array only if they are of the same dimension.
I won't give you the exact piece of code that you'll need, but hopefully now you can figure it out using the above piece of code.
I will also suggest playing around with all kinds of matrices, and their operations like replacing some elements, columns, and rows, as well as playing with matrix multiplication until you get the hang of it.
Some useful, commands include
numpy.random.rand(m, n) # will create a matrix of dimension m x n with pseudo-random numbers between 0 and 1
numpy.random.rand(m, n) # will create a matrix of dimension m x n with pseudo-random numbers between -1 and 1
numpy.eye(m) # will create a m x m identity matrix.
numpy.ones((m, n))
And make sure to read through the docs.
Good luck! And let your Python journey be a fun one. :)

Categories

Resources