Search code examples
pythonnumpyvectorization

How to define a matrix by vectorization (without for loop) in numpy?


I want to define an NxN matrix A, whose element A(i,j) is sin(i^2 + j).

In MATLAB, I can quickly define this matrix by employing vectorization.

N = 2000;
ii = 1:N;
A = sin(ii.^2 + ii');

How to achieve this in Python? Right now, I am using for loops, which are slow.

import numpy
N = 2000;
A = numpy.empty((N, N));
for i in range(1,N+1): 
    for j in range(1,N+1): 
        A[i-1][j-1] = numpy.sin(j + numpy.power(i, 2.))

Solution

  • Many things you can do in MATLAB have exact translations in numpy. Here's a handy cheat-sheet

    N = 2000 # remains unchanged
    ii = np.arange(1, N+1)  # In the cheat-sheet section Linear Algebra Equivalents 
    

    Now, there's a slight difference. In MATLAB, everything is treated as a matrix, so a 1-dimensional array is just a 1xN matrix, so transposing it is done just like any other matrix. In numpy, 1-dimensional arrays can't be transposed, so let's add a dummy dimension to ii:

    ii = ii[None, :]
    

    Now, ii is a 1xN matrix, so we can get A as:

    A = np.sin(ii**2 + ii.T);
    

    Numpy takes care of broadcasting the shapes (1, N) and (N, 1) and gives you a result that is (N, N)

    Note that a' in MATLAB is the conjugate transpose, which would be a.conj().T in numpy, but since these are all real numbers it makes no difference