1

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?

2
  • There probably isn't, because you are time-dependent, i.e. you need x[n] to be able to calculate x[n + 1]. Unless of course your process has a closed-form solution, but in which case you probably wouldn't be coding this in the first place, right? Commented Nov 4, 2014 at 20:42
  • You should consider pre-allocating x = np.zeros(n_range), though. Commented Nov 4, 2014 at 20:43

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.