我是 Matlab 用户,正在尝试切换到 Python。
如何使用 Numpy 在 for
循环中填充矩阵?
例如,矩阵有 2 列,for
循环的每次迭代都会添加一行新数据。
在 Matlab 中,这将是:
n = 100;
matrix = nan(n,2); % Pre-allocate matrix
for i = 1:n
matrix(i,:) = [3*i, i^2];
end
最佳答案
首先你必须使用
安装 numpy$ pip install numpy
然后下面的应该工作
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 所建议的那样
I = np.arange(n)
matrix = np.column_stack((3*I, I**2))
关于python - 使用for循环在numpy中填充二维矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40226192/