Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

python - Filling a 2D matrix in numpy using a for loop

I'm a Matlab user trying to switch to Python.

Using Numpy, how do I fill in a matrix inside a for loop?

For example, the matrix has 2 columns, and each iteration of the for loop adds a new row of data.

In Matlab, this would be:

n = 100;
matrix = nan(n,2); % Pre-allocate matrix
for i = 1:n
    matrix(i,:) = [3*i, i^2];
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First you have to install numpy using

$ pip install numpy

Then the following should work

import numpy as np    
n = 100
matrix = np.zeros((n,2)) # Pre-allocate matrix
for i in range(1,n):
    matrix[i,:] = [3*i, i**2]

A faster alternative:

col1 = np.arange(3,3*n,3)
col2 = np.arange(1,n)
matrix = np.hstack((col1.reshape(n-1,1), col2.reshape(n-1,1)))

Even faster, as Divakar suggested

I = np.arange(n)
matrix = np.column_stack((3*I, I**2))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...