Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a zero matrix without using numpy?

Tags:

python

Have looked all over but can't seem to find info if not on numpy. Need to create a 3 x 6 zero matrix using python not numpy & for the output to look exactly like this:

Matrix 3 by 6 with 0's:
00 00 00 00 00 00
00 00 00 00 00 00
00 00 00 00 00 00
like image 482
SMc Avatar asked Sep 11 '25 05:09

SMc


2 Answers

This works:

rows, cols = 3,6
my_matrix = [([0]*cols) for i in range(rows)]

Explanation:

  1. The expression ([0]*cols) represents each element of the list built by the list expression (the outer square brackets in [([0]*cols) for i in range(rows)])
  2. That expression ([0]*cols) produces a one-dimensional list of zeros (as many zeros as the value of cols)

So, effectively, the list expression builds a one-dimensional list of lists, where each inner list has cols zeros.

like image 90
fountainhead Avatar answered Sep 13 '25 20:09

fountainhead


I assume you know how to make a list in python: my_list = [0, 0, 0]. To make a list of lists, we can just nest list definitions inside of another list: nested_list = [[0, 0, 0], [0, 0, 0]]. Obviously you won't want to write the whole thing out, so we can abstract this into a function:

def make_zeros(n_rows: int, n_columns: int):
    matrix = []
    for i in range(n_rows):
        matrix.append([0] * n_columns)
    return matrix

This makes an outer list and then appends inner lists ("rows") to it one at a time. That was meant to be a very clear definition regardless of your level with Python, but you can shorten this a bit if you want by using list comprehensions:

def make_zeros(n_rows: int, n_columns: int):
    return [[0] * n_columns for _ in range(n_rows)]

Note that the inner lists are meant to be rows here, so you can easily access the rows:

matrix = make_zeros(3, 6)
matrix[0] # the first row

However, the "columns" consist of one element from each row; there isn't a list of these already, so if you wanted to get the first column, you have to do something like

col0 = [row[0] for row in matrix]

You could write a helper function to make this easier, but soon you'd be writing helper functions for all of the common matrix/array operations, and then you're reinventing the wheel that numpy has already made so nicely.

like image 23
Nathan Avatar answered Sep 13 '25 18:09

Nathan