Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a vector to a matrix in python

I want to append a vector to a matrix in python. I tried append or concatenate methods but I didn't get the answer. I was previously working with Matlab and there I used this:

m = zeros(10, 4) % define my matrix, 10x4
v = ones(10, 1) % my vecto, 10x1
c = [m,v] % so simple! the result is: 10x5 (the vector added as the last column)

How can I do that in python using numpy?

like image 290
Hadi Avatar asked Jan 07 '14 18:01

Hadi


1 Answers

You're looking for np.r_ and np.c_. (Think "column stack" and "row stack" (which are also functions) but with matlab-style range generations.)

Also see np.concatenate, np.vstack, np.hstack, np.dstack, np.row_stack, np.column_stack etc.

For example:

import numpy as np
m = np.zeros((10, 4))
v = np.ones((10, 1))
c = np.c_[m, v]

Yields:

array([[ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.]])

This is also equivalent to np.hstack([m, v]) or np.column_stack([m, v])

If you're not coming from matlab, hstack and column_stack probably seem much more readable and descriptive. (And they're arguably better in this case for that reason.)

However, np.c_ and np.r_ have additional functionality that folks coming from matlab tend to expect. For example:

In [7]: np.r_[1:5, 2]
Out[7]: array([1, 2, 3, 4, 2])

Or:

In [8]: np.c_[m, 0:10]
Out[8]:
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  2.],
       [ 0.,  0.,  0.,  0.,  3.],
       [ 0.,  0.,  0.,  0.,  4.],
       [ 0.,  0.,  0.,  0.,  5.],
       [ 0.,  0.,  0.,  0.,  6.],
       [ 0.,  0.,  0.,  0.,  7.],
       [ 0.,  0.,  0.,  0.,  8.],
       [ 0.,  0.,  0.,  0.,  9.]])

At any rate, for matlab folks, it's handy to know about np.r_ and np.c_ in addition to vstack, hstack, etc.

like image 198
Joe Kington Avatar answered Oct 20 '22 22:10

Joe Kington