简体   繁体   中英

operands could not be broadcast together with shapes (2,2) (2,100000)?

Trying to convert a matlab code to python and get the following error when trying to calculate the first and second data:

operands could not be broadcast together with shapes (2,2) (2,100000) 

when trying to rewrite this matlab snippet in vsc:

data=u*(s.^(1/2))*(randn(2,Ndata)); data=data+Ey;


The code that I have converted to python is:

Ky11 = 10
Ky22 = 1
rho = 0
Ky12 = np.sqrt(Ky11 * Ky22) * rho
Ky = np.array([[Ky11, Ky12], [Ky12, Ky22]])

Ey1 = 0
Ey2 = 0
Ey = np.array([[Ey1], [Ey2]])

Ndata = 100000

u, s, v = np.linalg.svd(Ky)
# Create a 2x2 diagonal matrix with the singular values of Ky (s) on the diagonal
s_matrix = np.diag(s)

# Compute the square root of each element of s_matrix and then multiply
# with u and np.random.randn(2, Ndata)
# Transpose u so that the dimensions match for element-wise multiplication
data = u.T * np.sqrt(s_matrix) * (np.random.randn(2, Ndata))
data = data + Ey

Ky_estimate = np.cov(data.T)

can anyone help with a solution?

I tried to compute the square root of s_matrix element-wise and then multiply with transposed u for dimesnions reasons but didn't get what I expected which was to get the code running without any errors. Have searched other stack overflow pages with "same" question but didn't solve my problem.

Are you trying to do matrix multiply? Use @ instead of * . Big Gotcha in Python. The operator * is element by element multiplication.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM