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

Time:11-29

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

CodePudding user response:

Many things you can do in MATLAB have exact translations in numpy. result

  • Related