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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With