Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Questions about numpy matrix in python

Tags:

python

numpy

#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?

like image 477
kaleo211 Avatar asked Feb 16 '23 05:02

kaleo211


1 Answers

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.

like image 162
tbekolay Avatar answered Feb 24 '23 21:02

tbekolay