使用for循环以numpy填充2D矩阵 [英] Filling a 2D matrix in numpy using a for loop
本文介绍了使用for循环以numpy填充2D矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是一个Matlab用户,试图切换到Python.
I'm a Matlab user trying to switch to Python.
使用Numpy,如何在for
循环内填充矩阵?
Using Numpy, how do I fill in a matrix inside a for
loop?
例如,矩阵有2列,并且for
循环的每次迭代都会添加新的一行数据.
For example, the matrix has 2 columns, and each iteration of the for
loop adds a new row of data.
在Matlab中,这将是:
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
推荐答案
首先,您必须使用
$ 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]
一种更快的选择:
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)))
按照Divakar的建议,甚至更快
Even faster, as Divakar suggested
I = np.arange(n)
matrix = np.column_stack((3*I, I**2))
这篇关于使用for循环以numpy填充2D矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文