4

I have a matrix

A = [[ 1.  1.]
    [ 1.  1.]]

and two arrays (a and b), every array contains 20 float numbers How can I multiply the using formula:

( x'    = A * ( x )
  y' )          y   

Is this correct? m = A * [a, b]

3
  • What's the relationship between a,b and (presumably) x and y? Does every value in a represent an x and every value in b represent a y for example? Commented Sep 18, 2013 at 20:32
  • there is no relation between a and b. Just arrays of uniformly generated numbers. Commented Sep 18, 2013 at 20:34
  • yes, every value of a represent x and every value of b represent y Commented Sep 18, 2013 at 20:34

1 Answer 1

4

Matrix multiplication with NumPy arrays can be done with np.dot. If X has shape (i,j) and Y has shape (j,k) then np.dot(X,Y) will be the matrix product and have shape (i,k). The last axis of X and the second-to-last axis of Y is multiplied and summed over.

Now, if a and b have shape (20,), then np.vstack([a,b]) has shape (2, 20):

In [66]: np.vstack([a,b]).shape
Out[66]: (2, 20)

You can think of np.vstack([a, b]) as a 2x20 matrix with the values of a on the first row, and the values of b on the second row.

Since A has shape (2,2), we can perform the matrix multiplication

m = np.dot(A, np.vstack([a,b]))

to arrive at an array of shape (2, 20). The first row of m contains the x' values, the second row contains the y' values.


NumPy also has a matrix subclass of ndarray (a special kind of NumPy array) which has convenient syntax for doing matrix multiplication with 2D arrays. If we define A to be a matrix (rather than a plain ndarray which is what np.array(...) creates), then matrix multiplication can be done with the * operator.

I show both ways (with A being a plain ndarray and A2 being a matrix) below:

import numpy as np

A = np.array([[1.,1.],[1.,1.]])
A2 = np.matrix([[1.,1.],[1.,1.]])
a = np.random.random(20)
b = np.random.random(20)
c = np.vstack([a,b])

m = np.dot(A, c)
m2 = A2 * c

assert np.allclose(m, m2)
Sign up to request clarification or add additional context in comments.

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.