Hi
As described in the following example, I want to introduce a number in a matrix name (number is a variable). I had a look on internet and I found a way but I'm wondering if there's something better than using "locals"?
import numpy as np
mat = np.zeros((2,3,3))
mat[0,:,:] = np.eye(3)
mat[1,:,:] = 2*np.eye(3)
print(mat)
for i in range(1,4):
my_var = 'mat{}'.format(i)
locals()[my_var] = i*mat
print("mat{} = {}".format(i, locals()[my_var]))
Thanks
Paul
Thanks for the answer
Nevertheless it highlights that I'm still not familiar with some aspects as one can see in my code (still trying to figure out)
mat = np.zeros((2,3,3))
mat[0,:,:] = np.eye(3)
mat[1,:,:] = 2*np.eye(3)
print(mat)
### using locals/globals
#for i in range(1,4):
# my_var = 'mat{}'.format(i)
# locals()[my_var] = i*mat
# print("mat{} = {}".format(i, locals()[my_var]))
## using a list
names = []
for i in range(1,4):
my_var = 'mat{}'.format(i)
names.append(my_var)
print("names[{}] = {}".format(i-1,names[i-1]))
names[i-1] = i * mat
print("type(name) = {}".format(type(names)))
print("type(name[0]) = {}".format(type(names[0])))
Paul
well, based on the above materials, I'm trying to understand how to proceed. It's the first time I've the opportunity to use a dictionnary and I'm performing tests.
I need to go deeper to figure out how it works, but I'm still wondering if the dictonnary is dynamically linked to key values (I do not understand why the RAM is much lower - but the last lines seem to say it's not the case, or maybe it's not "getsizeof" I need to use)
Paul
import numpy as np
from sys import getsizeof
n = 1_000
#n = 10
m = 2
X = np.random.random((n,m))
Y = np.random.random((n,m))
Z = np.random.random((n,m))
MAT_DICT = {'abscissa': X, 'ordinate': Y, 'applicate': Z}
print("X RAM = {}".format(getsizeof(X)))
print("Y RAM = {}".format(getsizeof(Y)))
print("Z RAM = {}".format(getsizeof(Z)))
print("MAT_DICT RAM = {}".format(getsizeof(MAT_DICT)))
my_var = 'abscissa'
if my_var in MAT_DICT:
print("'{}' is in MAT matrix".format(my_var))
else:
print("'{}' is not in MAT matrix".format(my_var))
## add new key/value
theta = np.random.random((n,2*m))
MAT_DICT.update({'Theta': theta})
## access to a key and work with
extract_key = MAT_DICT["abscissa"]
check = np.min(np.absolute(X - extract_key))
print("diff = {}".format(check))
## now update of 'abcissa" values
extract_key = 2.*MAT_DICT["abscissa"]
MAT_DICT["abscissa"] = extract_key # solution 1
extract_key = 10.*MAT_DICT["ordinate"]
MAT_DICT.update({'ordinate': extract_key}) #solution2
## what append if I modify one array: is MAT_DIC changed (in another word is it dynamically linked?)
X = np.empty(0)
print(MAT_DICT)