2

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?

2
  • What does "knoop" mean? Commented Sep 16, 2017 at 22:24
  • In MATLAB cells and matrices grow when you assign a value to a new index. That's not the case with Python. You have to append to lists. You need to preallocate arrays (like the np.zeros), or make new ones with concatenate. (Python dictionaries do grow with assignment.) Commented Sep 17, 2017 at 0:40

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

Your Answer

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.