Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Appending an array like in MATLAB

Tags:

python

matlab

How do I initialize and append an array like in MATLAB

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

Thanks.

like image 948
SEU Avatar asked Dec 08 '25 22:12

SEU


2 Answers

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.]]
like image 150
Josh Karpel Avatar answered Dec 10 '25 11:12

Josh Karpel


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.]])
like image 27
Akavall Avatar answered Dec 10 '25 12:12

Akavall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!