-1

I am doing a homework, where I need 20 matrices with shape (m,n), with names a_0, a_1, a_2, ..., a_19. At first they all can be filled with zeros. How can I do it using for? Working on Python

I can create them all by myself like:

a_0 = np.zeros((m,n))

...

a_19 = np.zeros((m,n))

but what if I need 1000 matrices?

Dmitrii Sidenko
  • 660
  • 6
  • 19
  • 2
    Does this answer your question? [How do you create different variable names while in a loop?](https://stackoverflow.com/questions/6181935/how-do-you-create-different-variable-names-while-in-a-loop) – Nils Nov 05 '19 at 09:14
  • It seems to me that it is easier to use a 3D-array instead of manually (or via for-loop) creating 20 2D arrays. Is it really impossible to use `a = np.zeros((10,m,n))`? – Tinu Nov 05 '19 at 09:24

3 Answers3

0

This is where lists could come in handy, as you do not require a particular name for each of your variables, just a way of accessing them. For a list you access the items by the index(number) in which they are ordered, starting from 0.

eg. you could write:

a = []
for i in range(1000):
    a.append(np.zeros((m,n))

Then you can later access them using their index in the list, e.g. a[0] for the first matrix, and a[241] for matrix number 242.

Alternatively you could just make a numpy array with an even higher dimension:

a = np.zeros((1000,m,n))

In the same way, a[0] would then be the first matrix.

M.T
  • 4,917
  • 4
  • 33
  • 52
  • This answer doesn't answer the question correctly as matrices are not named `with names a_0, a_1, a_2, ...,` as it is written in the question. Check my answer. – Roman Orac Nov 05 '19 at 09:34
  • @RomanOrac True, but it addresses the problem to be solved. It is seldom meaningful to have a dict representing what really should be a list, but with cumbersome notation. Likewise, I don't think we should advocate `exec` to new Python users. I believe this is a case of the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), and have answered accordingly – M.T Nov 05 '19 at 10:00
  • 1
    I agree with @M.T that this is clearly a case of the [XY problem](http://xyproblem.info/). Yes, we should attempt to answer questions as best we can, but sometimes that isn’t the right thing to do. – AMC Nov 05 '19 at 14:39
-1

You are currently using numpy arrays (numpy also has a matrix type), so I assume you need arrays.

To create an arbitrary number of arrays that can be retrieved with a name, I would use a python dictionary.

import numpy as np

N = 1000
m = 10
n = 10

arrays = {'a_%d' % i: np.zeros((m, n)) for i in range(N)}
Roman Orac
  • 1,562
  • 15
  • 18
-1
import numpy as np
N = 10
m, n = 10, 20
for i in range(N):
     exec( "a_%d = np.zeros((%d,%d))" % (i,m,n) )
fmonegaglia
  • 2,749
  • 2
  • 24
  • 34