Python绘制for循环内部for循环生成的数据

时间:2014-11-04 19:55:38

标签: python matlab numpy matplotlib

我正在尝试将此代码从Matlab转换为Python:

x(1) = 0.1;
j = 0;

for z = 2.8:0.0011:3.9
    j = j+1                 %Gives progress of calculation
    zz(j) = z;
    for n = 1:200
        x(n+1) = z*x(n)*(1 - x(n));
        xn(n,j) = x(n);
    end
end
h = plot(zz,xn(100:200,:),'r.');
set(h,'Markersize',3);
到目前为止我得到了这个:

import numpy as np
import matplotlib.pyplot as plt

x = []
x.append(0.1)
xn = []

j = 0

z_range = np.arange(2.8, 3.9, 0.0011)
n_range = range(0,200,1)

plt.figure()

for zz in z_range:
    j = j+1    
    print j  # Gives progress of calculation

    for n in n_range:
        w = zz * x[n] * (1.0-x[n])
        x.append(zz * x[n] * (1.0-x[n]))
        xn.append(w)

x = np.array(x)
xn = np.array(xn)

xn_matrix = xn.reshape((z_range.size, len(n_range)))
xn_mat = xn_matrix.T

plt.figure()
#for i in z_range:
#    plt.plot(z_range, xn_mat[0:i], 'r.')

plt.show()

我不确定这是否是将for循环从Matlab转换为Python的最佳方式,而且我似乎在绘制结果时遇到问题。 Matlab中的x(n+1) = z*x(n)*(1 - x(n));xn(n,j) = x(n);行让我烦恼,所以有人可以解释一下,如果有更有效的方式在Python中编写它吗?

1 个答案:

答案 0 :(得分:1)

import numpy as np
import matplotlib.pyplot as plt

x = 0.1
# preallocate xn
xn = np.zeros([1001, 200])
# linspace is better for a non-integer step
zz = np.linspace(2.8, 3.9, 1001)

# use enumerate instead of counting iterations
for j,z in enumerate(zz):
    print(j)
    for n in range(200):
        # use tuple unpacking so old values of x are unneeded
        xn[j,n], x = x, z*x*(1 - x)

plt.plot(zz, xn[:, 100:], 'r.')
plt.show()