How to 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 matrix of fixed size.
In python, I am working with numpy but I do not understand how to do this.
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
2 Answers 2
If you want a rank-3 Numpy array, and you know the shape of
f(i)in advance, you can pre-allocate the array:a = np.zeros((n,) + shape) for i in range(n): a[i] = f(i)If you just want a list (rather than 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 of
f(i)are first buffered in a dynamically-sized list before the Numpy array is built.
Comments
The best equivalent of a matlab cell array here is a list in python:
a = []
for i in range(n):
a.append(f(i))
fin advance?f.