-1
$\begingroup$

I am converting some MATLAB code in to python and have the encountered the error "ValueError Traceback (most recent call last) in 1 for ig in range(nbas): ----> 2 psi[:,ig] = np.polyval(np.array(pp[ig,:ig]),nodes)

ValueError: could not broadcast input array from shape (56,1) into shape (56) " I cannot find the issue with following code:

import numpy as np
import scipy.special as scl

##basis parameters (nbas<ngrid+1)
nbas = 54 #Basis set size in one dimension
ngrid = 56 #quadrature size

#Gauss-Hermite-Quadrature
#Hermite matrix
def hermipol(n):
    p = np.zeros((n+1,n+1))
    p[0][0] = 1
    if n == 0:
        p = np.array([[1,0],[2,0]], dtype = float)
    if n > 0:
        p[1][range(0,2)] = np.array([2,0])
        if n >=1:
            for k in range(2,n+1):
                p[k][range(n)] = 2*p[k-1][range(0,n)]
                p[k][range(2,n+1)] += -2*(k-1)*p[k-2][range(0,n-1)]
    for i in range(0,n+1):
        p[i,:] /= np.sqrt(np.sqrt(np.pi)*2**(i)*scl.factorial(i))

    return(p)
#Generation Gauss-Hermite Quadrature nodes and weights
def ghquad(n):
    return(np.polynomial.hermite.hermgauss(n))
[nodes,weights]  = ghquad(ngrid)

pp = hermipol(ngrid)


#Evaluation and store psi_i()(x,y)_k)
nodes = np.array([nodes]).T
weights = np.array([weights]).T
print(weights)
print(nodes)
np.shape(nodes)
psi = np.zeros((ngrid,nbas))
np.shape(psi)

for ig in range(nbas):
    psi[:,ig] = np.polyval(np.array(pp[ig,:ig]),nodes)

Any guidance would be greatly appreciated.

Thanks!

$\endgroup$
1
$\begingroup$

This post is better suited for Stackoverflow I think. Anyway you can simply solve your problem by changing psi[:,ig]to psi[:,ig:ig+1]. Then the left-hand side is truly a nx1 matrix, not just a vector of size n.

Or you can remove the line nodes = np.array([nodes]).T which is useless here, and causes Numpy to transform the array "nodes" (size n), into a 1xn array. Then the original psi[:,ig] works.

This kind of shape issue should easily be debugged by hand though !

$\endgroup$
1
  • $\begingroup$ Solved, thanks for the response! when I post questions in the future I will use the over. $\endgroup$ – New2Python Nov 25 '20 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.