-1

I want to create the matrices 1x5: matriz1, matriz2 and matriz3, with the values i + j, but my code doesn't work. Can someone help me?

import numpy as np

for i in range(3):
    name= 'matriz%d'%i
    name= np.zeros((1,5))

for i in range(3):
    name2 = 'matriz%d'%i
    for j in range(5):
        name2[j]=i+j

for i in range(3):
    name3 = 'matriz%d'%i
    print(name3)
Colin Basnett
  • 4,052
  • 2
  • 30
  • 49
Eduardo
  • 1
  • 1
  • 1
    If you ever think you need to choose variable names dynamically, you really need to use a data structure. Maybe a list of arrays or a 3D array instead of several 2D arrays. – user2357112 May 02 '16 at 18:03
  • thank you, I think this is a good idea. – Eduardo Aug 31 '16 at 19:13

1 Answers1

1

In Python, these 2 lines just assign two different objects to the variable name.

name= 'matriz%d'%i        # assign a string
name= np.zeros((1,5))     # assign an array

Some other languages have a mechanism that lets you use the string as variable name, e.g. $name = .... But in Python that is awkward, if not impossible. Instead you should use structures, such as a dictionary.

e.g.

adict = {}
for i in range(3):
   name= 'matriz%d'%i
   adict[name] = np.zeros((1,5))

You can then access this array via a dictionary reference like: adict['matriz3']

You could also use a list, and access individual arrays by number or list iteration:

alist = [np.zeros((1,5)) for i in range(3)]

for i,A in enumerate(alist):  # iteration with index
    A[:] = i+np.arange(5)
for a in alist:   # simple iteration
    print(a)
hpaulj
  • 221,503
  • 14
  • 230
  • 353