3

How do I initialize and append an array like in MATLAB

for i = 1:10
    myMat(i,:) = [1,2,3]
end

Thanks.

1
  • What do you mean by "array"? Commented Sep 7, 2017 at 22:53

3 Answers 3

1

You should look into numpy if you want an object similar to MATLAB's array constructs. There are many ways to construct arrays using numpy, but it sounds like you might be interested in joining or appending.

However, the strictest way to do what the MATLAB code in your question is doing is to construct the array first, then assign to it by slice:

import numpy as np

mat = np.empty((10, 3))
for idx in range(10):
    mat[idx, :] = [1, 2, 3]

print(mat)

This will output

[[ 1.  2.  3.]
 [ 1.  2.  3.]
 [ 1.  2.  3.]
 [ 1.  2.  3.]
 [ 1.  2.  3.]
 [ 1.  2.  3.]
 [ 1.  2.  3.]
 [ 1.  2.  3.]
 [ 1.  2.  3.]
 [ 1.  2.  3.]]
Sign up to request clarification or add additional context in comments.

Comments

1

Here is one approach:

In [18]: import numpy as np

In [19]: a = np.empty((10, 3))

In [20]: a[:] = np.array([1,2,3])

In [21]: a
Out[21]:
array([[ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.],
       [ 1.,  2.,  3.]])

Comments

1

If you are doing this in Python without any libraries, then you can initialize an array with a literal and list comprehension like so

myMat = [[1,2,3] for _ in range(10)]

If you are coming to Python from MATLAB I would suggest looking into the library numpy which exhibits behavior very similar to MatLab matricies with special "numpy arrays". In Numpy you might do this like so

import numpy as np
myMat = np.empty((10,3))
myMat[:] = [1,2,3]

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.