How do I create an array of matrices in python?
How do I create an array of matrices in python?
In MATLAB, I do something like this:
for i = 1:n
a{i} = f(i)
end
where f(i)
is a function that returns a random, fixed-size matrix.
In python, I am working with numpy, but I don't understand how to do it.
import numpy as np
a = np.array([])
for i in range(0, n):
# a.insert(i, f(i)) and does not work
# a[i] = f(i) and does not work
source to share
-
If you want a rank 3 Num-3 array and you know the shape ahead of time
f(i)
, you can preallocate the array:a = np.zeros((n,) + shape) for i in range(n): a[i] = f(i)
-
If you only want a list (not a Numpy array) of matrices, use a list comprehension:
a = [f(i) for i in range(n)]
-
Another way to get a Numpy array is to convert from the list comprehension above:
a = np.array([f(i) for i in range(n)])
However, this will be less efficient than # 1, because the results are
f(i)
first buffered in a dynamically sized list before the Numpy array is created.
source to share