Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 281
Vermillion Avatar asked Oct 24 '16 19:10

Vermillion


Video Answer


1 Answers

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))
like image 192
R. S. Nikhil Krishna Avatar answered Sep 17 '22 17:09

R. S. Nikhil Krishna