1

I have written the following code for creating a 2D array and filing the first element of each row. I am new to numpy. Is there a better way to do this?

y=np.zeros(N*T1).reshape(N,T1)
x = np.linspace(0,L,num = N)

for k in range(0,N):
    y[k][0] = np.sin(PI*x[k]/L)

2 Answers 2

3

Yes, since numpy vectorizes operations, you can just do:

y[:,0] = np.sin(np.pi * x / L)

Note that y[:,0] grabs the first column of y (the : in the first coordinate essentially means "grab all rows", and the 0 in the second coordinate means "from the column at index 0" (ie the first column)). Since np.sin(np.pi * x / L) is also an array, you can assign the latter to the former directly.

Sign up to request clarification or add additional context in comments.

Comments

2

This question is rather for codereview@stackexchange, but this snippet works!

import numpy as np

N = 1000 # arbitrary
T1 = 1000 # arbitrary
L = 10 # arbitrary

x = np.linspace(0,L,num = N)

# you don't need reshape here, give the size as a tuple!
y = np.zeros((N,T1)) 

# use a vectorized call here:
y[:,0] = np.sin(np.pi*x/L)

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.