How to efficiently generate this matrix in python
Question: I have already had a row vector a of dimension d which only contains elements
0 or 1.

I want generate a r by d matrix A, where A satisfies

    
    
    for column j = 1,2 .... d
    if a[j] = 1, then A[:,j] = 1. That's, the corresponding column will be all 1's 
    if a[j] = 0, then A[:,j] = 0. ....
    

I think it looks quite straightforward. But I don't know how to generate it
efficiently in python ( or in other languages).

Note that r = 1,000 and d = 100,000

(The reason why I want to generate this matrix A is that given another d by n
matrix B, C = A*B will be r by n which the rows of C correspond to the non-
zero elements in vector a.)


Answer: If you are going to be doing matrix multiplication or math in general in
Python, use [NumPy](http://www.numpy.org).

The rows of `A` all have the same value, so the _efficient_ way to calculate
it is to build only one row. You already have that row, `a`.

NumPy can also broadcast the values of an array, making a 1-dimensional vector
act like a 2-dimensional array with repeated values. This is memory-efficient
since you do not need to actually allocate space for the repeated values.

So, in NumPy you might perform the calculation like this:

    
    
    import numpy as np
    
    r, d, n = 1000, 100000, 1000
    a = np.random.randint(2, size=d)
    A = a
    print(A.shape)
    # (100000,)
    
    B = np.random.random((d, n))
    print(B.shape)
    # (100000, 1000)
    
    C = A.dot(B)
    print(C.shape)
    # (1000,)    
    

The result, `C` is "`of shape (n,)`" -- which is NumPy-talk for a 1D vector of
`n` elements -- rather than an array of shape `(r,n)` since, just like `A`,
all the rows have the same value. There is no need to repeat them.

