How do I initialize and append an array like in MATLAB
for i = 1:10
myMat(i,:) = [1,2,3]
end
Thanks.
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.]]
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.]])
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]