2

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
asked May 1, 2015 at 16:18
2
  • Do you know the shape of the array returned by f in advance? Commented May 1, 2015 at 16:34
  • Yes I know the dimensions of the matrix returned by f. Commented May 1, 2015 at 16:38

2 Answers 2

2
  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.

answered May 1, 2015 at 16:38
Sign up to request clarification or add additional context in comments.

Comments

2

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

a = []
for i in range(n):
 a.append(f(i))
answered May 1, 2015 at 16:35

1 Comment

left-over from the question.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.