Hot Articles

BarcodeBC > Articles > NxN Matix Python

1. What is NxN Matrix?

2. How to Create an NxN Matrix in Python?

3. How to Rotate an NxN Matrix in Python?

4. How to Create a 2D/3D Matrix of Random Numbers in Python?

5. How to Calculate the Entropy of an NxN Matrix in Python?

6. How to Copy an NxN Matrix into Page of NxNxN Matrix?

7. How to Check Whether an NxN Matrix is a Magic Square in Python?

8. How to Read an Outputted Fortran Binary NxNxN Matrix into Python?

9. DataFrame to an NxN Matrix?

Matrix is widely used when we do programming. For example, our data may only contains 1 row or 1 column, so there is no need to consider it as a matrix. But, what if we need to handle a large number of datas? Certainly, we need to handle those datas in NxN matrix. Obviously, we can deal with it in traditional way using python.

What is NxN matrix? To begin with, you should know about what is a matrix. A matrix is a linear map from a vector space V to a vector space W. You may also regard a matrix as a bilinear map from [; V\times W^*\to\mathbb{R} ;]. As for bilinear, I mean it is linear in both arguments.

You can extend the principle of a bilinear map to get a multilinear map: one which is linear in several arguments. When you say "NxNxN" that suggests a trilinear map [; T:V\times V\times V\to\mathbb{R} ;]. You can think of this as a function that eats a vector and spits out a matrix, or a function that eats three vectors and spits out a number.

Now, let's move on to more aspects of using the NxNxN matrix in python.

It is an easy task to create an NxN matrix in Python. Here, you will see two examples.

#build a list which consists of 6 lists, each of 9 items, all set to 0 w, h = 9, 6; Matrix = [[0 for x in range(w)] for y in range(h)]

#define empty matrix matrix=[] #total row is 4 for i in xrange(4): row=[] #total column is 4 for j in xrange(4): #adding 0 value for each column for this row row.append(0) #add fully defined column into the row matrix.append(row) print matrix

If you are looking for a solution for rotating an NxN matrix by 90 degrees clockwise in python, the following code example will nail it. Please note that your input matrix must be an NxN and the number of rows must equal to the number of columns.

def rotate(matrix): if matrix is None or len(matrix)<1: return else: if len(matrix)==1: return matrix else: #solution matrix soln = [row[:] for row in matrix] #size of matrix m = len(matrix[0]) for x in range(0,m): for j in range(0,m): soln[j][m-1-x] = matrix[x][j] return soln if __name__=="__main__": six = [["a","b","c"], [1,2,3], ["x","y","z"]] print "%s" % rotate(six)

If you want to create a matrix of random numbers in python, like 2d matrix and 3d matrix, this section is the right place. To perform this kind of task, NumPy library should be used. And you need to import NumPy library, using "import numpy as np".

import numpy as np random_matrix_array = np.random.rand(3, 4) print(random_matrix_array)

import numpy as np random_3d_matrix_array = np.random.rand(3, 4, 2) print(random_3d_matrix_array)

In this section, you will see two functions in Python for calculating the entropy of an NxN matrix in python. Let's see how it works.

def vn_eig_entropy(rho): import numpy as np from scipy import linalg as la import math as m EV = la.eigvals(rho) #drop zero eigenvalues so that log2 is defined my_list = [x for x in EV.tolist() if x] EV = np.array(my_list) log2_EV = np.matrix(np.log2(EV)) EV = np.matrix(EV) S = -np.dot(EV, log2_EV.H) return(S)

def von_neumann_entropy(rho): import numpy as np from scipy import linalg as la R = rho*(la.logm(rho)/la.logm(np.matrix([[2]]))) S = -np.matrix.trace(R) return(S)

It is not a tough task to copy an NxN Matrix into Page of NxNxN Matrix. Using Loops!

reps = 64; gradient = (1:reps); pattern = repmat(gradient,reps,1); threeD = zeros(reps,reps,reps); for Layer = 1: reps threeD(:,:,Layer) = pattern; end

Simple as that! Note: The for-loop must loop from 1 to reps which is indicated by 1:reps.

The following code example illustrates how to use a Python3 program to check whether a given matrix is magic matrix or not.

N = 3 #returns true if mat[][] is magic square, else returns false def isMagicSquare( mat) : #calculate the sum of the prime diagonal s = 0 for i in range(0, N) : s = s + mat[i][i] #for sums of rows for i in range(0, N) : rowSum = 0; for j in range(0, N) : rowSum += mat[i][j] if (rowSum != s) : return False #for sums of columns for i in range(0, N): colSum = 0 for j in range(0, N) : colSum += mat[j][i] if (s != colSum) : return False return True #driver code mat = [ [ 2, 7, 6 ], [ 9, 5, 1 ], [ 4, 3, 8 ] ] if (isMagicSquare(mat)) : print( "Magic Square") else : print( "Not a magic Square")

Two code examples are provided for reading an outputted fortran binary NxNxN matrix int Python.

fin=open('filename.dat','rb') output=[]for x in range(0,ndim): xarr=[] for y in range(0,ndim): yarr=[] for z in range(0,ndim): yarr.append(struct.unpack('i', fin.read(4))) xarr.append(yarr) output.append(xarr)

def readslice(inputfilename,ndim): shape = (ndim,ndim,ndim) fd = open(fname, 'rb') data = np.fromfile(file=fd, dtype=np.double).reshape(shape) fd.close() return data

from_comps = list(df['From']) to_comps = list(df['To']) transfer_rates = {} for from_comp in from_comps: for to_comp in to_comps: try: transfer_rates[from_comp, to_comp] = df.loc[(df['From'] == from_comp) & (df['To'] == to_comp)]['Rates'].values[0] except: pass all_comps = sorted(set(from_comps+to_comps)) model_matrix = pd.DataFrame(columns=sorted(all_comps),index=sorted(all_comps)) for rate in transfer_rates: model_matrix[rate[1]][rate[0]] = transfer_rates[rate] model_matrix.fillna(0, inplace=True)