Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Differentiating between row and column vectors

Is there a good way of differentiating between row and column vectors in python? So far I'm using numpy and scipy and what I see so far is that If I was to give one a vector, say

from numpy import * Vector = array([1,2,3]) 

they wouldn't be able to say weather I mean a row or a column vector. Moreover:

array([1,2,3]) == array([1,2,3]).transpose() True 

Which in "real world" is simply untrue. I realize that most of the functions on vectors from the mentioned modules don't need the differentiation. For example outer(a,b) or a.dot(b) but I'd like to differentiate for my own convenience.

like image 551
MarcinKonowalczyk Avatar asked Jul 02 '13 14:07

MarcinKonowalczyk


People also ask

How will you identify a row vectors from a column vectors?

A column vector is an nx1 matrix because it always has 1 column and some number of rows. A row vector is a 1xn matrix, as it has 1 row and some number of columns. This is the major difference between a column and a row vector.

How do you define a row vector in Python?

A row or column vector is in fact a two dimensional array (in which one of the two dimensions is 1). Thus, your tests should be done with array([[1, 2, 3]]) , instead, which is not equal to its transpose.

Are NumPy vectors row or column vectors?

So here is another example where NumPy arrays are not at all equivalent to vectors. Linear algebra makes a distinction between "row vectors" and "column vectors". There is no such distinction in NumPy. There are only n-dimensional arrays.


2 Answers

You can make the distinction explicit by adding another dimension to the array.

>>> a = np.array([1, 2, 3]) >>> a array([1, 2, 3]) >>> a.transpose() array([1, 2, 3]) >>> a.dot(a.transpose()) 14 

Now force it to be a column vector:

>>> a.shape = (3,1) >>> a array([[1],        [2],        [3]]) >>> a.transpose() array([[1, 2, 3]]) >>> a.dot(a.transpose()) array([[1, 2, 3],        [2, 4, 6],        [3, 6, 9]]) 

Another option is to use np.newaxis when you want to make the distinction:

>>> a = np.array([1, 2, 3]) >>> a array([1, 2, 3]) >>> a[:, np.newaxis] array([[1],        [2],        [3]]) >>> a[np.newaxis, :] array([[1, 2, 3]]) 
like image 128
bogatron Avatar answered Sep 30 '22 09:09

bogatron


Use double [] when writing your vectors.

Then, if you want a row vector:

row_vector = array([[1, 2, 3]])    # shape (1, 3) 

Or if you want a column vector:

col_vector = array([[1, 2, 3]]).T  # shape (3, 1) 
like image 24
davidA Avatar answered Sep 30 '22 09:09

davidA