【发布时间】:2021-12-21 18:40:42
【问题描述】:
对于numpy.matmul对dtype=object的操作,我有点困惑。
有人可以解释以下是如何工作的吗?特别是在最后一次操作“总计”中获得的内容。我使用这种方法(可能是错误的)将矩阵乘法替换为循环迭代。
为了大致了解我在做什么,这种计算的结果将用于生成 2 个热图,其中垂直为“z”,水平为“g_in”,颜色条值每次对应于“总计”值的第一个/第二个元素。这是对同时可变距离“z”和输入光束角“g_in”的ABCD射线传播的虚拟计算。
编辑的代码;
z = np.linspace(0, 10, 11) # distance
g_in = np.linspace(-5, 5, 11) #input angle
f_0, f_1 = 1, 1 #some constants
A = np.array([[1, z], [0, 1]], dtype = object)
B = np.array([[1, 0], [-1/(f_0), 1]], dtype = object)
C = np.array([[1, 2*f_0], [0, 1]], dtype = object)
D = np.array([[1, 0], [-1/(f_0), 1]], dtype = object)
E = np.array([[1, z], [0, 1]], dtype = object)
F = np.array([[1, 0], [-1/(f_1), 1]], dtype = object)
G = np.array([[1, f_1], [0, 1]], dtype = object)
H = np.matmul(G,F)
I = np.matmul(H,E)
J = np.matmul(I,D)
K = np.matmul(J,C)
L = np.matmul(K,B)
M = np.matmul(L, A)
print('Matrix M=',M)
col1 = np.empty((2, 1),dtype=object)
col1[:, 0] = [0, g_in]
print('Matrix col1[:,0]=',col1[:,0])
total = np.matmul(M, col1[:,0])
print('Matrix total=',total)
y_out = np.transpose(total[0].tolist())
g_out = np.transpose(total[1].tolist())
y_out_ = np.expand_dims(y_out, axis=0)
g_out_ = np.expand_dims(g_out, axis=0)
fig, ax1 = plt.subplots(nrows=1,
ncols=1,sharex=True,sharey=True, figsize=(8, 6))
f1=ax1.imshow(y_out_, extent=
[theta_in.min(),theta_in.max(),z_f.min(),z_f.max()],
vmin=y_out_.min(),vmax=y_out_.max(), aspect="auto",
cmap='YlGnBu')
cb1=fig.colorbar(f1,orientation='vertical')
cb1.set_label(r'$y_{out}$',size=15)
ax1.set_ylabel(r'z', fontsize=20)
ax1.tick_params(axis='both', which='major', labelsize=20)
ax1.tick_params(axis='both', which='minor', labelsize=20)
ax1.autoscale(tight=True)
fig, ax2 = plt.subplots(nrows=1, ncols=1,sharex=True,figsize
(8, 6))
f2=ax2.imshow(g_out_, extent=
[theta_in.min(),theta_in.max(),z_f.min(),z_f.max()],
vmin=g_out_.min(),vmax=g_out_.max(), aspect="auto",
cmap='YlGnBu')
cb2=fig.colorbar(f2,orientation='vertical')
cb2.set_label(r'$g_{out}$',size=15)
ax2.set_xlabel(r' Angle, $θ_{in}$', fontsize=20)
ax2.set_ylabel(r'z', fontsize=20)
ax2.tick_params(axis='both', which='major', labelsize=20)
ax2.tick_params(axis='both', which='minor', labelsize=20)
ax2.autoscale(tight=True)
以上代码输出;
非常感谢,
【问题讨论】:
-
对于
objectdtype,它取决于元素的+和*操作。它使用与手动进行矩阵乘法时相同的乘积和。objectdtype 数组的速度往往与列表理解计算相同。显示一个或多个结果,这样我们就可以在不自己运行代码的情况下看到发生了什么。 -
total是 3matmul的结果。太多了,无法想象。 -
@hpaulj 堆栈已更新!谢谢
标签: python numpy scientific-software