嗨,我是 python 新手,遇到以下问题。
下面使用两个矩阵进行简化:
我想通过以下步骤得到一个 6 x 4 矩阵
x=np.array([[1,2,3,4]])
c=np.random.rand(4,4)
y=np.zeros((4,4))
for i in range(4):
j=x[0,i]-x
y[i,:]=np.vstack(j)
z=y*c
weights=z.sum(axis=0)type here
但是,如果我尝试在嵌套循环中将其扩展为更大的维度 x(例如 6x4),则以下内容会出现在最后一行:
x=np.array([[1,2,3,4],[2,2,4,4],[0,5,3,4],[1,2,1,4],[1,0,3,4],[4,2,3,3]])
c=np.random.rand(4,4)
y=np.zeros((4,4))
z_weights_time=np.zeros((6,4))
for s in range(6):
d=x[[s],:]
for i in range(4):
j=d[0,i]-d
y[i,:]=np.vstack(j)
z=y*c
z_weights=z.sum(axis=0)
print("y= ",y)
print("c= ",c)
print("z_weights= ",z_weights)
z_weights_time[s,:]=np.vstack(z_weights)
预先感谢您的任何建议。
import numpy as np
x=np.array([[[1,2,3,4]],[[2,2,4,4]],[[0,5,3,4]],[[1,2,1,4]],[[1,0,3,4]],[[4,2,3,3]]])
c=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
y=np.zeros((4,4))
z_weights=np.zeros((6,4))
for row in range(6):
for col in range(4):
j=x[row,0,col]-x[row]
print(f'x[row,0,col] - x[row] = {x[row,0,col]} - {x[row]} = {j}')
y[col,:]=np.vstack(j)
z=y*c
print(f'z_weights@row{row}@row{row}=z.sum(axis=0 = {z.sum(axis=0)}')
z_weights[[row],:] = z.sum(axis=0)
print(f'z_weights = \n {z_weights}')