Filling a 2D matrix in numpy using a for loop

42,196

Solution 1

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))

Solution 2

This is very pythonic form to produce a list, which you can easily swap e.g. for np.array, set, generator etc.

n = 10

[[i*3, i**2] for i, i in zip(range(0,n), range(0,n))]

If you want to add another column it's no problem. Simply

[[i*3, i**2, i**(0.5)] for i, i in zip(range(0,n), range(0,n))]
Share:
42,196
Vermillion
Author by

Vermillion

Updated on July 09, 2022

Comments

  • Vermillion
    Vermillion almost 2 years

    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
    
  • Divakar
    Divakar over 7 years
    Or I = np.arange(n) and then np.column_stack((3*I, I**2)).
  • R. S. Nikhil Krishna
    R. S. Nikhil Krishna over 7 years
    Thanks for the tip :-)
  • TheBlackCat
    TheBlackCat over 7 years
    Keep in mind that these are not matrices, despite the variable name. They are arrays. Arrays are used in the same way matrices are, but work differently in a number of ways, such as supporting less than two dimensions and using element-by-element operations by default. Numpy provides a matrix class, but you shouldn't use it because most other tools expect a numpy array.