0

I'm trying to augment a matrix to solve an equation, yet have been unable to. And yes, I saw the "Augment a matrix in NumPy" question; it is not what I need.

So my problem: create an augmented matrix [ A b1 b2 ]

import numpy
a = numpy.array([[1,2],[5,12]])
b1 = numpy.array([-1,3]).T
b2 = numpy.array([1,-5]).T

I've tried the numpy.concatenate function, returns

ValueError: all the input arrays must have same number of dimensions

Is there a way to augment the matrix, such that I have one array of

[ 1 2 -1 1

5 12 3 -5 ]

If anyone knows, please inform me! Note that I was doing this in the IPython notebook

(btw, I know that I can't row reduce it with Numpy, it's a university problem, and just was doing the rest in IPython)

Thanks Matt

3 Answers 3

4

You can stack 1D arrays as if they were column vectors using the np.column_stack function. This should do what you are after:

>>> np.column_stack((a, b1, b2))
array([[ 1,  2, -1,  1],
       [ 5, 12,  3, -5]])
Sign up to request clarification or add additional context in comments.

Comments

0

I put your code into Ipython, and ask for the array shapes:

In [1]: a = numpy.array([[1,2],[5,12]])

In [2]: b1 = numpy.array([-1,3]).T

In [3]: b2 = numpy.array([1,-5]).T

In [4]: a.shape
Out[4]: (2, 2)

In [5]: b1.shape
Out[5]: (2,)

In [6]: b2.shape
Out[6]: (2,)

Notice a has 2 dimensions, the others 1. The .T does nothing on the 1d arrays.

Try making b1 a 2d. Also make sure you are concatenating on the right axis.

In [7]: b1 = numpy.array([[-1,3]]).T

In [9]: b1.shape
Out[9]: (2, 1)

Comments

0

numpy.concatenate() requires that all arrays have the same number of dimensions, so you have to augment the 1d vectors to 2d using None or numpy.newaxis like so:

>>> numpy.concatenate((a, b1[:,None], b2[:,None]), axis=1)
array([[ 1,  2, -1,  1],
       [ 5, 12,  3, -5]])

There are also the shorthands r_ and c_ for row/column concatenation, which mimic Matlab's notation:

>>> from numpy import c_
>>> c_[a, b1, b2]
array([[ 1,  2, -1,  1],
       [ 5, 12,  3, -5]])

Look up the source code to understand how they work ;-)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.