1

I came across weird results when computing large Numpy array.

A=np.matrix('1 2 3;3 4 7;8 9 6') 
A=([[1, 2, 3],
    [3, 4, 7],
    [8, 9, 6]])

A * A completes the dot product as expected:

A*A=([[ 31,  37,  35],
    [ 71,  85,  79],
    [ 83, 106, 123]])

But with a larger matrix 200X200 I get different response:

B=np.random.random_integers(0,10,(n,n))
B=array([[ 2,  0,  6, ...,  7,  3,  7],
   [ 4,  9,  1, ...,  6,  7,  5],
   [ 3,  1,  8, ...,  7,  3,  8],
   ..., 
   [ 8,  4, 10, ...,  5,  4,  4],
   [ 6,  6,  3, ...,  7,  2,  9],
   [ 2, 10, 10, ...,  5,  7,  4]])

Now multiply B with B

B*B
array([[  4,   0,  36, ...,  49,   9,  49],
   [ 16,  81,   1, ...,  36,  49,  25],
   [  9,   1,  64, ...,  49,   9,  64],
   ..., 
   [ 64,  16, 100, ...,  25,  16,  16],
   [ 36,  36,   9, ...,  49,   4,  81],
   [  4, 100, 100, ...,  25,  49,  16]])

I get each element squared and not a matrix * matrix What did I do different?

2
  • Is A a numpy array? Commented Oct 5, 2015 at 8:46
  • Yes, hopefully the above makes more sense. Commented Oct 5, 2015 at 8:51

2 Answers 2

4

You appear to have created A using the matrix type, while B is of the ndarray type (np.random.random_integers returns an array, not a matrix). The operator * performs matrix multiplication for the former and element-wise multiplication for the latter.

From the documentation of np.matrix:

A matrix is a specialized 2-D array that retains its 2-D nature through operations. It has certain special operators, such as * (matrix multiplication) and ** (matrix power).

As an aside, if you use two different types in the same operation, NumPy will use the operator belonging to the element with the highest priority:

>>> A = np.matrix('1 2 3;3 4 7;8 9 6') 
>>> B = np.array(A) # B is of array type, A is of matrix type
>>> A * B
matrix([[ 31,  37,  35],
        [ 71,  85,  79],
        [ 83, 106, 123]])

>>> B * A
matrix([[ 31,  37,  35],
        [ 71,  85,  79],
        [ 83, 106, 123]])

>>> A.__array_priority__
10.0
>>> B.__array_priority__
0.0
Sign up to request clarification or add additional context in comments.

Comments

2

You get this result since B is of type numpy.ndarray not numpy.matrix

>>> type(np.random.random_integers(0,10,(n,n)))
<type 'numpy.ndarray'>

Instead use

B=np.matrix(np.random.random_integers(0,10,(n,n)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.