1

I want to create a 2D numpy array of dimensions Nx2, in python. I want to create this by using 2 for loops. I can easily build this array in Matlab with the following code

matrix = [];

for i = 1:3
    for j = 1:4
        temp = [i, j];
        matrix = [matrix; temp];
    end
end

I have tried already numerous times, but failed. Usually, the error that I get is related to the sizes of arrays not matching when I run the for loops.

The output of the code is

matrix =

 1     1
 1     2
 1     3
 1     4
 2     1
 2     2
 2     3
 2     4
 3     1
 3     2
 3     3
 3     4
3
  • np.zeros((100,100)) create a 2-D array filled with zeros. It would be clear if you add expected output to the question. Commented Mar 23, 2020 at 17:12
  • You are right, I am going to add the expected output. What you mentioned might be the first step. Thank you Commented Mar 23, 2020 at 17:19
  • 1
    Remember in MATLAB everything is 2d. The [] is 0x0; [[]; [1,2]] joins that with a 1x2,expanding shapes as needed. In numpy arrays may be 0d,1d etc. np.concatenate is picky about matching dimensions. np.append is a poorly conceived front end to concatenate. Commented Mar 23, 2020 at 19:07

3 Answers 3

1

Here is a function that does what you want and uses two for loops. The reason that N is +1 and M is +1 is because in python the range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. So since we are starting at 1 instead of 0 we need to add 1 so that the actual range is correct. ie. 0,4 is a range of 4, but 1,4 is only really a range of 3. Hope that helps! -Brack

import numpy as np


def Nx2(N, M):
    matrix=[]
    n = N+ 1
    m= M + 1
    for i in range(1,n):
        for j in range(1,m):
            temp=[i,j]
            matrix.append(temp)
    final_matrix = np.array(matrix)
    return final_matrix
print(Nx2(3, 4))
Sign up to request clarification or add additional context in comments.

7 Comments

You're setting a global matrix outside the function (bad), but then returning it (good).
Also, this is not materially different from the answer posted by SurajSubramanian a quarter hour earlier.
In this instance, is it better to put the matrix=[] inside of the function? (always learning)
Absolutely. It's simply wrong not to. Try running your function twice.
It's nice to have those moments. By the way, don't forget to fix your indentation.
|
1
matrix= []

for i in range(1,4):
    for j in range(1,5):
        temp= [i,j]
        matrix.append(temp)

Finally you can convert the list of lists into a numpy array using matrix = np.array(matrix)

Comments

0

You really don't need a loop in either MATLAB or numpy for this. In both languages, explicit loops tend to be slow compared to the under-the-hood loops that run when you vectorize code. The additional problem with appending inside a loop is that each operation re-allocates the entire array to add the new element. You want to avoid appending and pre-allocate as much as possible.

Both packages have a meshgrid function. In numpy you could do:

ii = np.arange(3) + 1
jj = np.arange(4) + 1
j, i = np.meshgrid(jj, ii)

matrix = np.stack((i.ravel(), j.ravel()), axis=1)

In MATLAB, it would be very similar:

ii = 1:3;
jj = 1:4;
[i, j] = meshgrid(ii, jj);

matrix = [i(:) j(:)];

If you absolutely need to do this in a loop with constant reallocation, the MATLAB loop translates to numpy very easily. Instead of doing implicit vertcat, use np.append, or np.concatenate:

matrix = np.array((0, 2));

for i in range(1, 4)
    for j in range(1, 5)
        temp = [[i, j]]
        matrix = np.append(matrix, temp, axis=0)

1 Comment

I understand that with 'for' loops it is inefficient. I understand that I might be creating a bad habit, but the data dimensions that I am managing is not large, so it does not matter. The last piece of code you have put is what I have been trying to do. I get the following error, as I have so far. ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)

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.