Reputation: 3961
I am trying to convert this code from Matlab to 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);
and so far I have got this:
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()
I'm not sure if this is the best way to convert the for loops from Matlab into Python, and I seem to have problems with plotting the result. The x(n+1) = z*x(n)*(1 - x(n));
and xn(n,j) = x(n);
lines in Matlab are bugging me, so could someone please explain if there is a more efficient way of writing this in Python?
Upvotes: 1
Views: 328
Reputation: 1038
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()
Upvotes: 1