Experiment No 3 : Realization of Arrays and Matrices

 

3.Realization of Arrays and Matrices

Objective

  • Realize one dimensional array of real and complex numbers

  • stem and continuous plots of real arrays using matplotlib

  • Realization of two dimensional arrays and matrices and their visualizations with imshow/matshow/charts

  • Inverse of a square matrix and the solution of the matrix equation

  • Computation of the rank(ρ) and eigenvalues (λi) of A

Theory

Array of real and complex numbers

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).

Programe 1

# Python code to demonstrate the working of array

# creating an array

x = [1,2,3,4,5]

print(x) # Printing array

print("The first element is = ",x[0]) # printing first element

print("The first three elements are = ",x[0:3]) #printing first three elements

print("THe last element is =",x[-1]) #printing last element

Output 1

[1, 2, 3, 4, 5]

The first element is =  1

The first three elements are =  [1, 2, 3]

THe last element is = 5


Complex Numbers in Python

A complex number is represented by “ x + yi “. Python converts the real numbers x and y into complex using the function complex(x,y). The real part can be accessed using the function real() and the imaginary part can be represented by imag().


Programe 2

# Python code to demonstrate the working of 

# complex(), real() and imag() 

  

# Initializing real numbers 

x = 5

y = 3

  

# converting x and y into complex number 

z = complex(x,y); 

 

#printing complex number

print("The complex number is : ",z)

  

# printing real and imaginary part of complex number 

print ("The real part of complex number is : ",z.real) 

print ("The imaginary part of complex number is : ",z.imag) 


Output 2


The complex number is :  (5+3j)

The real part of complex number is :  5.0

The imaginary part of complex number is : 3.0


Program 3

 

# Python code to demonstrate the working of array

# creating an array with real and complex numbers

 

x = [5,complex(7,-1),3,complex(2,3),5]

 

print(x) # Printing array

 

Output 3


[5, (7-1j), 3, (2+3j), 5]


Stem and Continuous plots of real arrays using matplotlib

Matplotlib is a visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.

Programe 1

# program for plotting graph in python

# importing libraries 

from matplotlib.pyplot import *

from numpy import *

# import matplotlib.pyplot as plt 

# import numpy as np 

x = linspace(0, 2, 10) # assigning the values of x

y=x**2 # assigning the values of x^2

z=x**3 # assigning the values of x^3

fig1=figure()

plot(x, x, label='linear') # plotting x vs x graph

stem(x, y, label='quadratic',use_line_collection=True) #stemploting x vs x^2 graph

plot(x, z, label='cubic') #plotting x vs x^3 graph

xlabel('x label') # labeling x axis

ylabel('y label') # labeling y axis

title("Simple Plot") #titling the graph

axis([0,2,0,5]) #giving plot limit

legend() # enabling the legend

show(fig1) # displaying figures

Output 1

Matrix in Python

Python doesn't have a built-in type for matrices. However, we can treat a list of list as a matrix. For example: A 5×3  matrix is created, printed and displayed as an image using the code below. Its transpose is generated by the transpose() function.

Program

# program for assigning matrix values and displaying

# importing libraries 

from scipy import *

from pylab import *

x=mat([[1,2,3,4,5],[4,5,6,9,15],[7,8,9,23,25]])# assigning the values to matrix x

print (x) #printing matrix 

print (shape(x)) # printing size of the matrix

print (transpose(x)) # printing transpose of matrix

matshow(x) #Display an array as a matrix in a new figure window.

show() #Display all figures.

 

Output

[[ 1  2  3  4  5]

 [ 4  5  6  9 15]

 [ 7  8  9 23 25]]

(3, 5)

[[ 1  4  7]

 [ 2  5  8]

 [ 3  6  9]

 [ 4  9 23]

 [ 5 15 25]]


Inverse of a square matrix and the solution of the matrix equation

Inverse of a square matrix can be calculated with numpy function in python

Programe 

# program for assigning matrix values, inverse of matrix and displaying

# importing libraries 

from scipy import *

from pylab import *

from numpy import *

 

x=mat([[1,2],[4,5]])# assigning the values to matrix x

print ('The matrix is :') #printing matrix 

print (x)

print ('The size of the matrix is :',shape(x)) # printing size of the matrix

print ('Transpose of the matrix is :') #printing matrix 

print (transpose(x)) # printing transpose of matrix

show() #Display all figures.

print('Inverse of the matrix')

y = inv(x) # calculating inverse of the matrix

print(y)


Output

The matrix is :

[[1 2]

 [4 5]]

The size of the matrix is : (2, 2)

Transpose of the matrix is :

[[1 4]

 [2 5]]

Inverse of the matrix

[[-1.66666667  0.66666667]

 [ 1.33333333 -0.33333333]]

Solving Systems of Linear Equations

Consider the system of linear equations

3x + 2y - 5z =  12

 x - 3y + 2z = -13

5x -  y + 4z =  10

Write the coefficients in an A matrix.

 

x

y

z

 

 

3

2

-5

 

 

1

-3

2

 

 

5

-1

4

 


Write the variables in an X matrix.

 

x

 

 

y

 

 

z

 

Write the constants in a b matrix.

 

12

 

 

-13

 

 

10

 



Solve the values of x, y, z from the equation

[A][X] = [b]

[X] = A-1 [b]


Programe 

# program for assigning matrix values, inverse of matrix and displaying

# importing libraries 

from scipy import *

from pylab import *

from numpy import *

 

A=array([[3,2,-5],[1,-3,2],[5,-1,4]])# assigning the values to matrix A from the equaton

b = array([12,-13,10]) # assigning the values of b matrix

 

print("A matrix is")

print(A) # printing the A matrix

print("b matrix is")

print(b) #printing then b matrix

X=inv(A).dot(b) # calculating the values of x,y,z

print("X matrix is")

print(X) # printing the X matrix 

# printing each values

print("the value of x is :",round(X[0],2))

print("the value of y is :",round(X[1],2))

print("the value of z is :",round(X[2],2))

 

Output

A matrix is

[[ 3  2 -5]

 [ 1 -3  2]

 [ 5 -1  4]]

b matrix is

[ 12 -13  10]

X matrix is

[2.17045455 5.89772727 1.26136364]

the value of x is : 2.17

the value of y is : 5.9

the value of z is : 1.26


# program for assigning matrix valies and displaying

# importing libraries 

from scipy import *

from pylab import *

from numpy.linalg import *

 

x=mat([[1,2],[4,5]])# assigning the values to matrix x

print ('The matrix is :') #printing matrix 

print (x)

print ('The size of the matrix is :',shape(x)) # printing size of the matrix

print ('Transpose of the matrix is :') #printing matrix 

print (transpose(x)) # printing transpose of matrix

show() #Display all figures.

print('Inverse of the matrix')

y = inv(x) # calculating inverse of the matrix

print(y)

 


# programe for ploting graph in python

# importing libraries 

import matplotlib.pyplot as plt 

import numpy as np 

 

from scipy import *

from pylab import *

x=mat([[1,2,3,4,5],[4,5,6,9,15],[7,8,9,23,25]])

print (x)

print (shape(x))

print (transpose(x))

matshow(x)

show()

Computation of the rank(ρ) and eigenvalues (λi) of A

The rank of a matrix is defined as (a) the maximum number of linearly independent column vectors in the matrix or (b) the maximum number of linearly independent row vectors in the matrix.

In linear algebra, an eigenvector or characteristic vector of a linear transformation is a nonzero vector that changes at most by a scalar factor when that linear transformation is applied to it. The corresponding eigenvalue, often denoted by λi, is the factor by which the eigenvector is scaled.

Program

# Importing numpy as np

from numpy import *

# Assigning the matrix A 

A = array([[-6, 3],

           [4,5]])

 

# Finding Rank of a A

Rnk = matrix_rank(A)

print("Rank of A:",Rnk) #Printing the rank of the matrix

#finding the eigenvectors of A

Lam = eig(A)

print("Eigen values are :",Lam[0]) #printing the eigenvectors


Output

Rank of A: 2

Eigen values are : [-7.  6.]


Singular value decomposition

Singular value decomposition takes a rectangular matrix of gene expression data (defined as A, where A is a n x p matrix) in which the n rows represents the genes, and the p columns represents the experimental conditions. The SVD theorem states:

Anxp= Unxn Snxp VTpxp

Where U & V are orthogonal matrices

Where the columns of U are the left singular vectors (gene coefficient vectors); S (the same dimensions as A) has singular values and is diagonal (mode amplitudes); and VT has rows that are the right singular vectors (expression level vectors). The SVD represents an expansion of the original data in a coordinate system where the covariance matrix is diagonal.


 Calculating the SVD consists of finding the eigenvalues and eigenvectors of AAT and ATA. The eigenvectors of ATA make up the columns of V , the eigenvectors of AAT  make up the columns of U. Also, the singular values in S are square roots of eigenvalues from AAT or ATA.  The singular values are the diagonal entries of the S matrix and are arranged in descending order. The singular values are always real numbers. If the matrix A is a real matrix, then U and V are also real.

To understand how to solve for SVD, let’s take the example of the matrix

In this example the matrix is a 4x2 matrix. We know that for an n x n matrix W, then a nonzero vector x is the eigenvector of W if:

W x = l x

For some scalar λ.  Then the scalar λ is called an eigenvalue of A, and x is said to be an eigenvector of A corresponding to l.

 So to find the eigenvalues of the above entity we compute matrices AAT and ATA.  As previously stated , the eigenvectors of AAT  make up the columns of U so we can do the following analysis to find U.

Now that we have a n x n matrix we can determine the eigenvalues of the matrix W.

Since W x = l x then   (W- lI) x = 0


For a unique set of eigenvalues the determinant of the matrix (W-λI) must be equal to zero.  Thus from the solution of the characteristic equation, |W-λI|=0 we obtain:

λ=0, λ=0; λ = 15+Ö221.5 ~ 29.883;  λ = 15-Ö221.5 ~ 0.117 (four eigenvalues since it is a fourth  degree polynomial).  This value can be used to determine the eigenvector that can be placed in the columns of U.  Thus we obtain the following equations:

19.883 x1 + 14 x2 = 0

14 x1 + 9.883 x2 = 0

x3  = 0

x4 = 0

 

Upon simplifying the first two equations we obtain a ratio which relates the value of x1 to x2.   The values of x1 and x2 are chosen such that the elements of the S are the square roots of the eigenvalues.   Thus a solution that satisfies the above equation x1 = -0.58 and x2 = 0.82 and x3 = x4 = 0 (this is the second column of the U matrix).

 

Substituting the other eigenvalue we obtain:

            -9.883 x1 + 14 x2 = 0

14 x1 - 19.883 x2 = 0

x3  = 0

x4 = 0

 

Thus a solution that satisfies this set of equations is x1 = 0.82 and x2 = -0.58 and x3 = x4 = 0 (this is the first column of the U matrix). Combining these we obtain:

 

 

 

Similarly ATA makes up the columns of V so we can do a similar analysis to find the value of V.

and similarly we obtain the expression:

 

 

Finally as mentioned previously the S is the square root of the eigenvalues from AAT or ATA.  and can be obtained directly giving us:

 

Program for SVD

# Program for singular value decomposition

# importing libraries

import numpy as np

# assigning the matrix A

A = np.array([[2,4],[1,3],[0,0],[0,0]])

print("A =")

print(A)

[U,S,V] = np.linalg.svd(a)

print("U =")

print(U)

print("S =")

print(S)

print("V =")

print(V)

Output

A =

[[2 4]

 [1 3]

 [0 0]

 [0 0]]

U =

[[-0.81741556 -0.57604844  0.          0.        ]

 [-0.57604844  0.81741556  0.          0.        ]

 [ 0.          0.          1.          0.        ]

 [ 0.          0.          0.          1.        ]]

S =

[5.4649857  0.36596619]

V =

[[-0.40455358 -0.9145143 ]

 [-0.9145143   0.40455358]]


Inference

  • Realized and understood one dimensional array of real and complex numbers

  • Plotted real arrays using  stem and continuous plots with matplotlib

  • Realized two dimensional arrays and matrices and their visualizations with imshow/matshow/charts

  • Calculated Inverse of a square matrix and the solution of the matrix equation using python

  • Computed the rank(ρ) and eigenvalues (λi) of matix A




References
https://web.mit.edu/be.400/www/SVD/Singular_Value_Decomposition.htm

No comments:

Post a Comment

Signals & System Lect 15 | Stable & Unstable Systems | Solved examples

  ECT 204 SIGNALS AND SYSTEMS Topics covered  00:00 - Introduction to Stable & unstable Systems 01:08 - BIBO criteria 03:38 Problem No 1...