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

Question:

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.))

Answers:

This can be done with the use of numpy which allows for vectorization of arrays and array-like operations. I’m sure this can be reduced in size, but we can create an array in x and y before making a grid out of these points. We then apply the entire grid to the function A=sin(i**2+j). We then get (I assume ii' is the same as the transpose of ii?)

import numpy as np # Import library
import matplotlib.pyplot as plt # To visualize
N = 2000 # NxN 
x = np.linspace(0,1,N)*np.pi #Define two arrays of length N
y = np.linspace(0,1,N)*np.pi

X, Y = np.meshgrid(x,y) #Create a NxN grid with arrays

A = np.sin(X**2+Y) # Apply grid to function

plt.imshow(A.T, origin='lower', aspect='auto') #Show that it has worked
plt.show()

which gives (updated to match your result in the range [0,pi])

result

Answered By: t.o.

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

Answered By: Pranav Hosangadi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.