Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterative array creation in matlab and python

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?

like image 466
Gaurav Girish Avatar asked Jul 25 '26 03:07

Gaurav Girish


1 Answers

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

like image 138
Andreas K. Avatar answered Jul 27 '26 16:07

Andreas K.