Joe strum
Joe strum

Reputation: 33

Storing a variable amount of matrices in python using numpy

I am trying to recreate some code from MatLab using numpy, and I cannot find out how to store a variable amount of matrices. In MatLab I used the following code:

for i = 1:rows
    K{i} = zeros(5,4);  %create 5x4 matrix

    K{i}(1,1)= ET(i,1); %put knoop i in table
    K{i}(1,3)= ET(i,2); %put knoop j in table    

    ... *do some stuff with it*

end

What i assumed i needed to do was to create a List of matrices, but I've only been able to store single arrays in list, not matrices. Something like this, but then working:

for i in range(ET.shape[0]):

   K[[i]] = np.zeros((5, 4))

   K[[i]][1, 2] = ET[i, 2]

I've tried looking on https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html but it didn't help me.

Looking through somewhat simular questions a dirty method seems to be using globals, and than changing the variable name, like this:

for x in range(0, 9):
     globals()['string%s' % x] = 'Hello'
     print(string3)

Is this the best way for me to achieve my goal, or is there a proper way of storing multiple matrices in a variable? Or am i wanting something that I shouldnt want to do because python has a different way of handeling it?

Upvotes: 2

Views: 6358

Answers (2)

nalyd88
nalyd88

Reputation: 5138

In the MATLAB code you are using a Cell array. Cells are generic containers. The equivalent in Python is a regular list - not a numpy structure. You can create your numpy arrays and then store them in a list like so:

import numpy as np
array1 = np.array([1, 2, 3, 4])    # Numpy array (1D)
array2 = np.matrix([[4,5],[6,7]])  # Numpy matrix
array3 = np.zeros((3,4))           # 2D numpy array
array_list = [a1, a2, a3]          # List containing the numpy objects

So your code would need to be modified to look more like this:

K = []
for i in range(rows):
    K.append(np.zeros((5,4)))  # create 5x4 matrix

    K[i][1,1]= ET[i,1]  # put knoop i in table
    K[i][1,3]= ET[i,2]  # put knoop j in table    

    ... *do some stuff with it*

If you are just getting started with scientific computing in Python this article is helpful.

Upvotes: 3

littleO
littleO

Reputation: 1002

How about something like this:

import numpy as np

myList = []
for i in range(100):
    mtrx = np.zeros((5,4))
    mtrx[1,2] = 7
    mtrx[3,0] = -5
    myList.append(mtrx)

Upvotes: 3

Related Questions