3

I am trying to convert a snippet of MATLAB code into python, the MATLAB code is as follows:

M = 0;
for k=1:i
    M = [M,        M,      M;
    M, ones(3^(k-1)), M;
    M,        M,      M];
end

which creates a 2d array that mimics a sierpinski carpet
my python implementation is as such:

M = 0   
for x in range(1,count):
        square = np.array([[M, M, M], [M, np.ones([3**(x-1),3**(x-1)]), M], [M, M, M]])

I know I am missing something with the nature of how the arrays are concatenated, since my python output is coming up with more than two dimensions. How would I maintain a 2d array that creates the same output?

1
  • See this Commented Mar 1, 2018 at 8:48

2 Answers 2

2

You can use block()

import numpy as np
M = 0
for k in range(count):
    I = np.ones((3**k, 3**k))
    M = np.block([[M, M, M],
                  [M, I, M],
                  [M, M, M]])

For example, for count = 4, you get the following output (plotted with matplotlib -- if you are interested in making such plots let me know):

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

This block is relatively new, 1.13.0. Previously we had to use bmat or a set of nested concatenate calls. It works by recursively calling concatenate on the nested list.
0

You need to set the M as two dimensional array first, then you can use concatenate, based on its axis. Next, in python, range is up to count exclusive. Thus, you need to add 1.

Your code is modified into the following:

import numpy as np
import matplotlib.pylab as plt

def sierpinski(count=3):
    M = np.array([[0]])   
    for x in range(1,count+1):
        M = np.concatenate((np.concatenate((M, M, M), axis=1),
            np.concatenate((M, np.ones([3**(x-1),3**(x-1)]), M), axis=1),
            np.concatenate((M, M, M), axis=1)),axis=0)
    return M

# run the code
M=sierpinski()
plt.spy(M)
plt.show()

When you run it produces beautiful Sierpinski Gasket: enter image description here

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.