2

Say I want to multiply a matrix by a vector:

[1 2 3]   [10]
[4 5 6] * [11]
[7 8 9]   [12]

In Python using Numpy I would do it like this:

from numpy import *

A = matrix(
    [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]])

B = matrix(
    [[10], [11], [12]])

print(A * B)

However as you can see, in order to define matrix B correctly, I have to type [[10], [11], [12]], and that is a bit tedious. Is there something that just constructs a vector, so I could type something like vector([10, 11, 12]) instead of matrix([[10], [11], [12]])?

user8578415
  • 341
  • 1
  • 4
  • 8

6 Answers6

4

You can create B as a numpy array and then use the method dot

B=np.array([10,11,12])
print(A.dot(B)) #Use A.dot(B).T if you need to keep the original dimension
obchardon
  • 10,614
  • 1
  • 17
  • 33
3

You can just transpose the matrix:

In [1]: import numpy as np

In [2]: A = np.matrix(
   ...:     [[1, 2, 3],
   ...:      [4, 5, 6],
   ...:      [7, 8, 9]])
   ...:

In [3]: B = np.matrix([10, 11, 12]).T

In [4]: print(A * B)
[[ 68]
 [167]
 [266]]
awesoon
  • 32,469
  • 11
  • 74
  • 99
  • a note to the OP: always use the matrix class with caution. it does not behave like an array at times when you think it would. – Paul H May 03 '18 at 14:29
3

You can also use the c_ column assembly object:

>>> np.c_[[10,11,12]]
array([[10],
       [11],
       [12]])

or

>>> np.c_[10:13]
array([[10],
       [11],
       [12]])

or with linspace semantics

>>> np.c_[10:12:3j]
array([[10.],
       [11.],
       [12.]])
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
1

An easy option is to create a new axis of dimension None:

import numpy as np

A = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
    ])

B = np.array([ 10, 11, 12 ])

print(A * B[:,None])
Kefeng91
  • 802
  • 6
  • 10
1

Slightly different than the other answers, but here are my 2 cents :)

Python's zip might be of help here!

In [13]: blist = [10, 11, 12]

In [14]: B = matrix(zip(blist))

In [15]: print B
[[10]
 [11]
 [12]]
Agey
  • 891
  • 8
  • 17
0

Another option is np.reshape:

B = np.array([10, 11, 12]).reshape(-1, 1)

>>> array([[10],
           [11],
           [12]])
sjw
  • 6,213
  • 2
  • 24
  • 39