Sqrti
Sqrti

Reputation: 33

dot product of 2-D array and 1-D array is different from matrix and 1-D array

I used the numpy dot function to calculate the product of a 2D and a 1D array. I noticed that when the 2D array is of type matrix while the 1D array is of type ndarray, the result returned by the dot function is not the same as when I pass it a 2D array of type ndarray.

Question: Why are the results different?

Short example

import numpy as np
a=[[1,2],
   [3,4],
   [5,6]]
e=np.array([1,2])
b=np.array(a)
print("Ndarrray:%s"%(type(b)))
print(b)
print("Dim of ndarray %d"%(np.ndim(b)))
be=np.dot(b,e)
print(be)
print("Dim of array*array %d\n"%(np.ndim(be)))

c=np.mat(a)
print("Matrix:%s"%(type(c)))
print(c)
print("Dim of matrix %d"%(np.ndim(c)))
ce=np.dot(c,e)
print(ce)
print("Dim of matrix*array %d"%(np.ndim(ce)))
Ndarrray:<class 'numpy.ndarray'>
[[1 2]
 [3 4]
 [5 6]]
Dim of ndarray 2
[ 5 11 17]
Dim of array*array 1

Matrix:<class 'numpy.matrix'>
[[1 2]
 [3 4]
 [5 6]]
Dim of matrix 2
[[ 5 11 17]]
Dim of matrix*array 2

Upvotes: 3

Views: 209

Answers (1)

Nikaido
Nikaido

Reputation: 4629

First of all, for the matrix class:

Note:
It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.

https://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html

That's because the first element in the dot product is of matrix type, and therefore you receive a matrix as output. But if you use the shape method to get the "real" size of your matrix you get a coherent result:

import numpy as np
a=[[1,2],
   [3,4],
   [5,6]]
e=np.array([1,2])
b=np.array(a)
print("Ndarrray:%s"%(type(b)))
print(b)
print("Dim of ndarray %d"%(np.ndim(b)))
be=np.dot(b,e)
print(be)
print("Dim of array*array %d\n"%(np.ndim(be)))

c=np.mat(a)
print("Matrix:%s"%(type(c)))
print(c)
print("Dim of matrix %d"%(np.ndim(c)))
ce=np.dot(c,e)
print(ce)
print("Dim of matrix*array %d"%(np.ndim(ce))) 
print("Dim of matrix*array ",(ce.shape)) # -> ('Dim of matrix*array ', (1, 3))
print(type(ce)) # <class 'numpy.matrixlib.defmatrix.matrix'>

You have a matrix of shape (1,3), which is in fact a vector (dim 1, because you have 1 row and 3 columns)

Basically, to get the dimensions of matrix instance you should use shape, not ndim

To make it more clear, if you define an empty matrix you get as default always 2 dims:

c=np.mat([])
print(c.ndim) # 2

Probably it has been intended in this way because we start to talk of a Matrix when we have at least 2-dims

Upvotes: 4

Related Questions