Kira
Kira

Reputation: 343

How to create an array of matrices in python?

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

Upvotes: 2

Views: 494

Answers (2)

Daniel
Daniel

Reputation: 42778

The best equivalent of a matlab cell array here is a list in python:

a = []
for i in range(n):
    a.append(f(i))

Upvotes: 2

Will Vousden
Will Vousden

Reputation: 33408

  1. 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)
    
  2. 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)]
    
  3. 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.

Upvotes: 2

Related Questions