Python - can a Matrix be a variable? [duplicate]

I want to convert some Fortran code into Python but there is this block of code:

  do i=1,maxcomp
     do j=1,maxcomp
        do k=1,nvbin
           ng(i,j,k) = 0
        end do
     end do
  end do

these are do-loops, in Python known as for-loops. The line in the middle (ng(i,j,k) = 0) is a matrix and attached to it is a value, 0 in this case and through the for-loops many "variables" get created and you can refer them with the matrices.

Is there something similar in Python so i can convert the code?


In Python for 2-dimensional matrices or higher dimensional tensors, the pratic is to use the external package numpy. The call ng=np.zeros((maxcomp, maxcomp, nvbin), dtype='float') alone will do it for you.

!pip install numpy. # will install numpy in virtual environments it is nor present. 
import numpy as np
ng=np.zeros((maxcomp, maxcomp, nvbin), dtype='float')

Without resorting to Numpy, there are no native types to represent matrices, but it is easy to customize a class to do so. One of the more intuitive ways is to use nested lists - (also one of the worst ways). Even dictionaries can work nice as matrices, as long as you control the indices and taking care that they lie inside the desired boundaries.

A dictionary can retrieve a value given comma separated numbers (internally they work as a tuple). So, you can just create an empty dict and use the same code you've seem in Fortran:

ng = {}
for i in range(maxcomp):
   for j in range(maxcomp):
       for k i range(nvbin):
           ng[i,j,k] = 0

Just take care that dictionaries map arbitrary keys to arbitrary values: they are not constrained to have 3-coordinates mapping to a scalar. But you can create any code you want expecting a dictionary with this structure, and it will work as a matrix (given you pass the sizes for each axis as separate parameters). If the code uses the .get method to retrieve values, you do not even need to fill the structure with 0s beforehand: each non-assigned value can be "seen" as 0 in a call like ng.get((i, j, k), 0)


if you want to do matrices, you should do it with numpy:

import numpy as np
templist = []
for i in range(1,maxcomp):
    for j in range(1,maxcomp):
        for k in range(1,nvbin):
           templist.append([i,j,k])
matrix = np.matrix(templist)

using numpy :

import numpy as np

ng = np.zeros((maxcomp,maxcomp,nvbin))

and probably need to decrease maxcomp and nvbin by 1 , as in python indices start from 0