Array of arrays (Python/NumPy)

Array of arrays (Python/NumPy)

It seems strange that you would write arrays without commas (is that a MATLAB syntax?)

Have you tried going through NumPys documentation on multi-dimensional arrays?

It seems NumPy has a Python-like append method to add items to a NumPy n-dimensional array:

>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)

>>> p = np.append(p, [[7],[8],[9]],1)

>>> p
array([[1, 2, 7], [3, 4, 8], [5, 6, 9]])

It has also been answered already

From the documentation for MATLAB users:

You could use a matrix constructor which takes a string in the form of a matrix MATLAB literal:

mat(1 2 3; 4 5 6)


matrix([1 2 3; 4 5 6])

Please give it a try and tell me how it goes.

Youll have problems creating lists without commas. It shouldnt be too hard to transform your data so that it uses commas as separating character.

Once you have commas in there, its a relatively simple list creation operations:

array1 = [1,2,3]
array2 = [4,5,6]

array3 = [array1, array2]

array4 = [7,8,9]
array5 = [10,11,12]

array3 = [array3, [array4, array5]]

When testing we get:


[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

And if we test with indexing it works correctly reading the matrix as made up of 2 rows and 2 columns:

[4, 5, 6]

[10, 11, 12]

Hope that helps.

Array of arrays (Python/NumPy)

If the file is only numerical values separated by tabs, try using the csv library:
(you can set the delimiter to t)

If you have a textual file in which every line represents a row in a matrix and has integers separated by spacestabs, wrapped by a arrayname = […] syntax, you should do something like:

import re
f = open(your-filename, rb)
result_matrix = []
for line in f.readlines():
    match = re.match(rs*w+s+=s+[(.*?)]s*, line)
    if match is None:
        pass # line syntax is wrong - ignore the line
    values_as_strings =
    result_matrix.append(map(int, values_as_strings))

Leave a Reply

Your email address will not be published. Required fields are marked *