作为一名C ++程序员,我习惯于以C ++风格访问向量:
for (i=0; i<max_x; i++) {
for (j=0; j<max_y; j++) {
vec[i][j] = real(complex_number(j+i*max_x))
}
}
现在我有了Python
x = np.linspace(x1, x2, step)
y = np.linspace(y1, y2, step)
X, Y = np.meshgrid(x, y)
Z = x + 1j*y
for z in Z:
FZ = complex_function(z)
如何以“pythonic”方式完成与C ++代码相同的操作?感谢
编辑:检查重塑功能并重新确定我的代码,我注意到从2D阵列到1D阵列和返回的转换问题。主要问题是我有一个函数接受一个复杂的数组z_list并返回一个复杂的数组。我需要在网格上绘制,我计划使用matplotlib,但matplotlib需要一个2D数组,该数组上的每个点都有值。如何在不生成2D阵列的情况下将其重新整形为1D阵列,并将阵列重新整形为2D?感谢。
答案 0 :(得分:2)
使用reshape
将1D数组转换为2D(或任何其他形状)。
>>> x_max = 12
>>> y_max = 4
>>> vec1d = np.arange(x_max*y_max, dtype=complex)
>>> vec1d.reshape([x_max, y_max])
array([[ 0.+0.j, 1.+0.j, 2.+0.j, 3.+0.j],
[ 4.+0.j, 5.+0.j, 6.+0.j, 7.+0.j],
[ 8.+0.j, 9.+0.j, 10.+0.j, 11.+0.j],
[ 12.+0.j, 13.+0.j, 14.+0.j, 15.+0.j],
[ 16.+0.j, 17.+0.j, 18.+0.j, 19.+0.j],
[ 20.+0.j, 21.+0.j, 22.+0.j, 23.+0.j],
[ 24.+0.j, 25.+0.j, 26.+0.j, 27.+0.j],
[ 28.+0.j, 29.+0.j, 30.+0.j, 31.+0.j],
[ 32.+0.j, 33.+0.j, 34.+0.j, 35.+0.j],
[ 36.+0.j, 37.+0.j, 38.+0.j, 39.+0.j],
[ 40.+0.j, 41.+0.j, 42.+0.j, 43.+0.j],
[ 44.+0.j, 45.+0.j, 46.+0.j, 47.+0.j]])
答案 1 :(得分:1)
而不是做Z = x + 1j*y
然后重塑,你可以这样做:
Z = np.zeros((ydim, xdim), dtype=complex)
Z.real, Z.imag = X, Y
我认为可能更有效(总共减少操作)。
答案 2 :(得分:0)
使用重塑
>>> Z.reshape(5,10)
array([[ 0.00000000 +0.j , 0.20408163 +0.20408163j,
0.40816327 +0.40816327j, 0.61224490 +0.6122449j ,
0.81632653 +0.81632653j, 1.02040816 +1.02040816j,
1.22448980 +1.2244898j , 1.42857143 +1.42857143j,
1.63265306 +1.63265306j, 1.83673469 +1.83673469j],
[ 2.04081633 +2.04081633j, 2.24489796 +2.24489796j,
2.44897959 +2.44897959j, 2.65306122 +2.65306122j,
2.85714286 +2.85714286j, 3.06122449 +3.06122449j,
3.26530612 +3.26530612j, 3.46938776 +3.46938776j,
3.67346939 +3.67346939j, 3.87755102 +3.87755102j],
[ 4.08163265 +4.08163265j, 4.28571429 +4.28571429j,
4.48979592 +4.48979592j, 4.69387755 +4.69387755j,
4.89795918 +4.89795918j, 5.10204082 +5.10204082j,
5.30612245 +5.30612245j, 5.51020408 +5.51020408j,
5.71428571 +5.71428571j, 5.91836735 +5.91836735j],
[ 6.12244898 +6.12244898j, 6.32653061 +6.32653061j,
6.53061224 +6.53061224j, 6.73469388 +6.73469388j,
6.93877551 +6.93877551j, 7.14285714 +7.14285714j,
7.34693878 +7.34693878j, 7.55102041 +7.55102041j,
7.75510204 +7.75510204j, 7.95918367 +7.95918367j],
[ 8.16326531 +8.16326531j, 8.36734694 +8.36734694j,
8.57142857 +8.57142857j, 8.77551020 +8.7755102j ,
8.97959184 +8.97959184j, 9.18367347 +9.18367347j,
9.38775510 +9.3877551j , 9.59183673 +9.59183673j,
9.79591837 +9.79591837j, 10.00000000+10.j ]])