Federico Gentile - 10 months ago 44

Python Question

I am studying python on my own and I want to create a matrix; by reading in the internet I found many ways to define a matrix and I decided to select these 2 methodologies:

`import numpy as np`

# Method 1

w, h = 5, 5

M = [[0 for x in range(w)] for y in range(h)]

M[1][2] = 100 # ok

m = M[:,2] # <----- Why is it not possible?

# Method 2

A = np.zeros((5, 5))

A[1][2] = 100 # ok

a = A[:,2] # <----- Why is it possible?

In both cases I am able to construct the matrix but the problem arises when I try to define an array by selecting one column of the matrix itself. While in the second case I am able to define

`a`

`m`

What should I do in order to extract a column out of M?

I believe the reason resides in the fact that M and A are not the same type of variable but honestly I don't understand the difference and therefore I don't know how to proceed.

`<class 'list'> # M`

<class 'numpy.ndarray'> # A

Answer

`A`

and `M`

are very different objects, as you have also discovered yourself. They might store the same information, but they do it differently and allow you to manipulate it in different ways. They have different interfaces, which means you have to interact with them differently. This affects the operations that you are allowed to perform on them.

`M`

is a list of lists. It contains several elements, each of which is a list of integers. `M`

doesn't *know* that it is a matrix, it only *knows* that it contains a fixed number of elements. You can get individual lists out with `M[i]`

, but then to get the actual matrix element you have to work with the list you got. Note, that you can do `M.append('abc')`

, after which `M`

will stop being a matrix. To actually use `M`

as a matrix you need to resort to trics, like using `col = [row[i] for row in M]`

to get columns, and if you want e.g. to compute the determinant, it is going to be rather painful.

`A`

is a matrix and so it can inspect its whole contents, and you can get any element you want out of it, including a single column. It is impossible to append one element to it. You can use the whole NumPy library to perform operations on it as a matrix, such as computing determinants with `np.det(A)`

.

Source (Stackoverflow)