kaleo211
kaleo211

Reputation: 43

Questions about numpy matrix in python

#these are defined as [a b]
hyperplanes = np.mat([[0.7071,    0.7071, 1], 
                      [-0.7071,   0.7071, 1],
                      [0.7071,   -0.7071, 1],
                      [-0.7071,  -0.7071, 1]]);

a = hyperplanes[:][:,0:2].T;
b = hyperplanes[:,2];

what does these denotes of [:][:,0:2] mean? What is the final results of a and b?

Upvotes: 4

Views: 99

Answers (1)

tbekolay
tbekolay

Reputation: 18547

We can use the interactive interpreter to find this out.

In [3]: hyperplanes = np.mat([[0.7071,    0.7071, 1], 
   ...:                       [-0.7071,   0.7071, 1],
   ...:                       [0.7071,   -0.7071, 1],
   ...:                       [-0.7071,  -0.7071, 1]])

Notice that we don't need semicolons at the end of lines in Python.

In [4]: hyperplanes
Out[4]: 
matrix([[ 0.7071,  0.7071,  1.    ],
        [-0.7071,  0.7071,  1.    ],
        [ 0.7071, -0.7071,  1.    ],
        [-0.7071, -0.7071,  1.    ]])

We get back a matrix object. NumPy typically uses an ndarray (you would do np.array instead of np.mat above), but in this case, everything is the same whether it's a matrix or ndarray.

Let's look at a.

In [7]: hyperplanes[:][:,0:2].T
Out[7]: 
matrix([[ 0.7071, -0.7071,  0.7071, -0.7071],
        [ 0.7071,  0.7071, -0.7071, -0.7071]])

The slicing on this is a little strange. Notice that:

In [9]: hyperplanes[:]
Out[9]: 
matrix([[ 0.7071,  0.7071,  1.    ],
        [-0.7071,  0.7071,  1.    ],
        [ 0.7071, -0.7071,  1.    ],
        [-0.7071, -0.7071,  1.    ]])

In [20]: np.all(hyperplanes == hyperplanes[:])
Out[20]: True

In other words, you don't need the [:] in there at all. Then, we're left with hyperplanes[:,0:2].T. The [:,0:2] can be simplified to [:,:2], which mean that we want to get all of the rows in hyperplanes, but only the first two columns.

In [14]: hyperplanes[:,:2]
Out[14]: 
matrix([[ 0.7071,  0.7071],
        [-0.7071,  0.7071],
        [ 0.7071, -0.7071],
        [-0.7071, -0.7071]])

.T gives us the transpose.

In [15]: hyperplanes[:,:2].T
Out[15]: 
matrix([[ 0.7071, -0.7071,  0.7071, -0.7071],
        [ 0.7071,  0.7071, -0.7071, -0.7071]])

Finally, b = hyperplanes[:,2] gives us all of the rows, and the second column. In other words, all elements in column 2.

In [21]: hyperplanes[:,2]
Out[21]: 
matrix([[ 1.],
        [ 1.],
        [ 1.],
        [ 1.]])

Since Python is an interpreted language, it's easy to try things out for ourself and figure out what's going on. In the future, if you're stuck, go back to the interpreter, and try things out -- change some numbers, take off the .T, etc.

Upvotes: 8

Related Questions