User Tools

Site Tools


k29:k29.3:k29.3.3:start

29.3.3 Matrix class

The class Matrix (gb.gsl) implements a two-dimensional matrix with real or complex coefficients.

29.3.3.1 Matrix

  • A matrix can be understood as a rectangular arrangement of different mathematical elements.
  • For the Matrix class in Gambas, the mathematical elements are either real or complex numbers. If complex numbers are used, this must be specified explicitly.
  • The real or complex numbers aij in a matrix are called coefficients.

Here you can see the elements of a square matrix with complex coefficients:

B1

29.3.3.2 Properties

The Matrix class has three properties:

PropertyData typeDescription
HandlePointerReturns a pointer to the internal GSL matrix object.
HeightIntegerReturns a dimension (height = number of rows) of a matrix.
WidthIntegerReturns the other dimension (width = number of columns) of a matrix.

Table 29.3.3.2.1 : Properties of the Matrix class

29.3.3.3 Methods

The Matrix class has these methods:

MethodReturn typeDescription
Column ( iColumn As Integer )VectorReturns the column of a matrix selected via 'iColumn' as a vector.
SetColumn ( iColumn As Integer, vVector As Vector )-Fills the selected column 'iColumn' of a matrix with the elements of a vector 'vVector'.
Row ( iRow As Integer )VectorReturns the row of a matrix selected via 'iRow' as a vector.
SetRow ( iRow As Integer, vVector As Vector )-Fills the selected row 'iColumn' of a matrix with the elements of a vector 'vVector'.
Conj ( ) MatrixReturns the conjugate matrix for a given matrix.
Copy ( ) MatrixReturns a copy of a matrix.
Inv ( )MatrixReturns the inverted matrix for a given matrix.
Trans ( )MatrixReturns the transposed matrix to the given matrix.
Det ( )VariantReturns the determinant of a given square matrix.
ToString ( [ Local As Boolean ] )StringReturns the matrix as a string representation - depending on the 'Local' parameter.

Table 29.3.3.3.1 : Methods of the Matrix class

Notes:

  • The copy of a matrix is an independent matrix object.
  • The transposed AT of a matrix A is created by setting the row vectors of A as column vectors of AT. If A = AT, A is called symmetric (along the diagonal).
  • The conjugate A of a matrix A contains the complex conjugate coefficients of the matrix. In particular, if the matrix A is real, A = A.
  • If the Local parameter has the value True, numbers are output in the local notation, while the default value False formats the string so that it can be evaluated by the Eval(..) function.
  • The determinant of a matrix can only be calculated for (square) matrices where the number of rows is equal to the number of columns.
  • The data type of the function value of the Det() method is of type Variant, because the determinant can be a real number or a complex number.

29.3.3.4 Creating a matrix

There are different ways to create matrices:

  • (A) Declaration of a variable of the data type matrix with implicit value assignment.
  • (B) Declaration of a variable of the data type matrix and subsequent assignment of the elements.
  • (C) Create a copy of an existing matrix.
  • (D) Use the static method Matrix.Identity.

Example A

Public mMatrix1 As Matrix

mMatrix1 = New Matrix(3, 3, True) '-- Columns, rows - complex coefficients (all zero)
mMatrix2 = [[1, 1.4, 7 + 2i], [2, 2, 2], [-1, -2i, -3]] ' Inline-Matrix

Dim Theta As Float = Pi / 2 '-- Radian measure of 90°
Dim A As Matrix = [[Cos(Theta), -Sin(Theta)], [Sin(Theta), Cos(Theta)]] 

Example B

Public mMatrix As Matrix

Private Sub CreateAndShowMatrix()

  mMatrix = New Matrix(5, 5, True) '-- columns, rows
  mMatrix.SetRow(0, [1, 1, 1, 7 + 2i, 8])
  mMatrix.SetRow(1, [2, 2, 2, 4, 5])
  mMatrix.SetRow(2, [1, 0, 3, 9, 5])
  mMatrix.SetRow(3, [1, 0.2, 4, 4, -3])
  mMatrix.SetRow(4, [-1, -2i, -3, 4, 5 + 1i]) '-- Attention: 5 + i --> 5+1i

End

Example C

Dim cMatrix As New Matrix
cMatrix = mMatrix.Copy() '-- Copy of the original matrix: mMatrix
lblValue.Text = cMatrix.ToString(False) '-- Display the elements of the matrix copy as a string

Example D

The static method Matrix.Identity also creates a new matrix:

Static Function Identity ( [ matColumn As Integer, matRow As Integer, Complex As Boolean ] ) As Matrix
  • 'matColumn' is the number of columns, two by default.
  • 'matRow' is the number of rows, two by default.
  • If 'Complex' has the value True, the matrix coefficients can be complex numbers. Even if Complex initially has the value False, the coefficients will be automatically converted to complex numbers if required.
  • The identity or unit matrix has zeros everywhere outside the diagonal and ones on the diagonal. Only such matrices are returned by Matrix.Identity().

Example 1:

Public mMatrix As Matrix
mMatrix = Matrix.Identity(3, 3, False) '-- Real coefficients
mMatrix = [[1, 1.4, 7], [2, 2, 2], [-1, -2.88, -3]]

Example 2:

Dim hMatrix As Matrix
  
hMatrix = Matrix.Identity(5, 3, True)
Print hMatrix.ToString(False)

The content of the generated matrix is displayed in the console of the IDE as a character string:

[[1,0,0,0,0],[0,1,0,0,0],[0,0,1,0,0]]

29.3.3.5 Inserting and displaying matrix elements

In examples A and B, you have already learnt how to insert elements into a matrix. Another option utilises the fact that you can use the Matrix class like a read-write array whose elements can be read or set:

To set selected coefficients in a matrix:

Dim mMatrix As Matrix 
Dim vValue As Variant 
mMatrix [ iRow As Integer, iColumn As Integer ] = vValue '-- For array operations, first row, then column

mMatrix[3,5] = 23.5
mMatrix[4,1] = 5-3i

The elements of a matrix can be displayed row by row, column by column, as a single matrix element, as a character string or completely in a grid component.

Display of all matrix elements in a TableView:

Private Sub MatrixToTableView(aMatrix As Matrix)
  Dim i, j As Integer
   
  TableView1.Clear
  TableView1.Rows.Count =  aMatrix.Height
  For i = 0 To aMatrix.Height - 1
     For j = 0 To aMatrix.Width - 1
         TableView1[i, j].Text = aMatrix[i, j]
     Next '-- j
  Next '-- i   
  
End

This source code section demonstrates several of the above options for displaying matrix elements:

Private Sub ShowMatrixElements()  
  Dim iCount, z, s As Integer
 
'-- Display matrix and selected matrix elements
  Print "Display of the line vectors:\n"  
  For iCount = 1 To mMatrix.Height '-- Number of lines
    Print mMatrix.Row(icount - 1)
  Next
 
  Print
 
  Print "Display of the column vectors:\n"
  For iCount = 1 To mMatrix.Width '-- Number of columns
    Print mMatrix.Column(icount - 1)
  Next
 
  Print
 
  Print "Display of the matrix elements:\n"
  For z = 1 To mMatrix.Height   '-- Number of lines
    For s = 1 To mMatrix.Width  '-- Number of columns
      Print mMatrix[z - 1, s - 1],
    Next
    Print
  Next
 
  Print  
 
  Print "Display of diagonal elements (special case):\n"
  Print mMatrix[0, 0],
  Print mMatrix[1, 1],
  Print mMatrix[2, 2],
  Print mMatrix[3, 3],
  Print mMatrix[4, 4]  
 
  Print  
 
  Print "Display of the matrix elements in a string:\n"
  Print mMatrix.ToString(False)
 
End

This is the output in the console of the Gambas IDE:

Anzeige der Zeilen-Vektoren:
 
[1 1 1 7+2i 8]
[2 2 2 4 5]
[1 0 3 9 5]
[1 0,2 4 4 -3]
[-1 -2i -3 4 5+i]
 
Anzeige der Spalten-Vektoren:
 
[1 2 1 1 -1]
[1 2 0 0,2 -2i]
[1 2 3 4 -3]
[7+2i 4 9 4 4]
[8 5 5 -3 5+i]
 
Anzeige der Matrix-Elemente:
 
1	1	1	7+2i	8	
2	2	2	4	5	
1	0	3	9	5	
1	0,2	4	4	-3	
-1	-2i	-3	4	5+i	
 
Anzeige der Diagonal-Elemente (Sonderfall):
 
1	2	3	4	5+i
 
Anzeige der Matrix-Elemente in einem String:
 
[[1,1,1,7+2i,8],[2,2,2,4,5],[1,0,3,9,5],[1,0.2,4,4,-3],[-1,-2i,-3,4,5+1i]]

29.3.3.6 Operations and relations

The following operations are explained for matrices: addition, subtraction, multiplication of 2 matrices, multiplication by a number and multiplication by a vector as a matrix-vector product. This special product is explained in more detail in the excursus below. The direct comparison and the test for inequality exist as relations between 2 matrices.

It is also possible to compare the string representations of matrices:

IF GetErrorVector(aArgumente).ToString(True) = "[0 0 0 0 0 0 0]" THEN ...

29.3.3.7 Project

The following project implements all variants for creating a matrix and all properties and methods of the Matrix class have been used.

  • Default:
    A matrix (original) is generated, which is used for all operations and also for the relations.
  • The original matrix and the result matrices are displayed in an (editable) TableView.
  • Calculated numbers or vectors or comparison results are displayed in a label.
  • When entering complex numbers - in the general representation a+bi - the value for b must be entered explicitly.
  • For example, the representations 1+1i or 3-1i are correct, while 3-i produces an error. Incorrect entries for changing the coefficients of the original matrix in the TableView are handled.

B2

Figure 29.3.3.7.1: Demonstration of working with matrices

The sufficiently commented source code for the project presented is given here in full:

' Gambas class file
 
Public mMatrix As New Matrix(5, 5, True)
 
Public Sub Form_Open()
  FMain.Center()
  FMain.Resizable = False    
  btnMatrixCompare.Text = "Matrix comparison: Original " & String.Chr(8596) & " Modified copy"
 
  SetTableViewProperty()
  CreateAndShowMatrix()
 
End
 
Public Sub btnShowDimMatrix_Click()
  lblValue.Text = "Columns: " & mMatrix.Width & "     |     rows: " & mMatrix.Height
End
 
Public Sub btnMatrixInv_Click()
  Dim invMatrix As New Matrix(mMatrix.Width, mMatrix.Height, True)
 
  invMatrix = mMatrix.Inv()
  MatrixToTableView(invMatrix)  
End
 
Public Sub btnMatrixTrans_Click()
  Dim transMatrix As New Matrix(mMatrix.Width, mMatrix.Height, True)
 
  transMatrix = mMatrix.Trans()
  MatrixToTableView(transMatrix)  
End
 
Public Sub btnMatrixConj_Click()
  Dim conjMatrix As New Matrix(mMatrix.Width, mMatrix.Height, True)
 
  conjMatrix = mMatrix.Conj()
  MatrixToTableView(conjMatrix)
End
 
Public Sub btnMatrixDet_Click()
  If mMatrix.Height <> mMatrix.Width Then
     Message.Error("It is not possible to calculate the determinant!<br>The matrix is <b>not</b> quadratic.")
     Return
  Else
     lblValue.Text = "D  =  " & mMatrix.Det()
  Endif
End
 
Public Sub btnMatrixMulVector_Click()
  Dim copyMatrix As New Matrix
 
  copyMatrix = mMatrix.Copy() ' Copy of the original matrix: mMatrix
  lblValue.Text = copyMatrix([1, 2, 0, 4, 3]).ToString(False)
 
End
 
Public Sub btnMatrixMulValue_Click()
  MatrixToTableView(3 * mMatrix)
End
 
Public Sub btnMatrixAddMatrix_Click()
  MatrixToTableView(mMatrix + mMatrix.Copy())
End
 
Public Sub btnMatrixCompare_Click()
  Dim cMatrix As Matrix
 
  cMatrix = mMatrix.Copy()
  cMatrix[1, 1] = 222 '-- A change to the copy
 
  If cMatrix = mMatrix Then
     lblValue.Text = "The matrices are equal."
  Else
     lblValue.Text = "The matrices are NOT the same!"
  Endif
 
End
 
Public Sub btnReset_Click()  
  lblValue.Text = ""
  CreateAndShowMatrix()
  ShowMatrixElements()    
End
 
Public Sub TableView1_Save(Row As Integer, Column As Integer, ValueEdit As String)  
  TableView1[Row, Column].Text = ValueEdit ' Change cell content of TableView
  If ValueEdit Not Match "[0-9][iI]" Then ValueEdit = Replace$(Replace$(ValueEdit, "i", "1i"), "I", "1I")
  mMatrix[Row, Column] = Eval(ValueEdit) ' Apply changes to matrix as well
End
 
Public Sub TableView1_Click()
  TableView1.Edit()
End
 
Private Sub CreateAndShowMatrix()
 
  mMatrix = [[1, 1, 1, 7+2i, 8],[2, 2, 2, 4, 5],[1, 0, 3, 9, 5],[1, 0.2, 4, 4, -3], [-1, -2i, -3, 4, 5+1i]]
 
' Fill matrix with start values - alternative
  ' mMatrix.SetRow(0, [1, 1, 1, 7 + 2i, 8])
  ' mMatrix.SetRow(1, [2, 2, 2, 4, 5])
  ' mMatrix.SetRow(2, [1, 0, 3, 9, 5])
  ' mMatrix.SetRow(3, [1, 0.2, 4, 4, -3])
  ' mMatrix.SetRow(4, [-1, -2i, -3, 4, 5 + 1i]) ' Achtung: 5 + i --> 5+1i
 
' Display matrix elements in the TableView
  MatrixToTableView(mMatrix) 
 
End
 
Private Sub MatrixToTableView(aMatrix As Matrix)
  Dim i, j As Integer
 
  lblValue.Text = ""
  TableView1.Clear
  TableView1.Rows.Count = aMatrix.Height ' spinboxRows.Value
  For i = 0 To aMatrix.Height - 1
     For j = 0 To aMatrix.Width - 1
         TableView1[i, j].Text = aMatrix[i, j]
     Next '-- j
  Next '-- i   
 
End
 
Private Sub SetTableViewProperty()
 
  TableView1.AutoResize = True
  TableView1.Mode = Select.Single
  TableView1.Resizable = True      ' The column width can be changed with the mouse
  TableView1.AutoResize = True     ' The last column has the available (remaining) width
  TableView1.Background = &HF5FFE6 ' light green   
  TableView1.NoKeyboard = False    ' If TRUE, then arrow keys WITHOUT effect for navigating in grid columns
 
  TableView1.Rows.Count = mMatrix.Height
  TableView1.Columns.Count = mMatrix.Width
 
End

29.3.3.8 Excursus

(A)
A binary clock is presented in chapter '20.3.1.3 Example 3 - Clock with binary display':

B3

Figure 29.3.3.8.1: Clock with binary display

The rectangular arrangement of the bits can easily be mapped to a matrix as a data structure - as the following source code excerpt shows:

Public Function SetTimeMatrix() As Matrix 
  Dim iRow, iColumn As Integer 
  Dim sZeitHMS As String 
  Dim vTime As New Vector(6, False) 
  Dim mBitMatrix As New Matrix(6, 4, False) 
 
  sZeitHMS = Replace(Str(Time(Now())), ":", "") 
 
  For iRow = 1 To mBitMatrix.Height ' 6 
      vTime[iRow - 1] = Mid(sZeitHMS, iRow, 1) 
      For iColumn = 1 To mBitMatrix.Width ' 4 
          mBitMatrix[iRow - 1, iColumn - 1] = Mid(Str(Bin(vTime[iRow - 1], 4)), iColumn, 1) 
    Next '-- iColumn 
  Next '-- iRow 
 
  Return mBitMatrix 
 
End

(B)
The Matrix class can also be used like a function:

Function Matrix( vector As Vector ) As Vector 

The matrix is multiplied by a vector vector and returns a vector as the product:

Public Sub MatrixMulVector(aMatrix As Matrix, aVector As Vector)
  Dim vResult As Vector
 
  vResult = aMatrix(aVector)                        '-- Matrix vector product
  lblValue.Text = vResult.ToString(False)           '-- Display of the result vector as a string
' lblValue.Text = aMatrix(aVector).ToString(False)  '-- No use of the local variable vResult
End
 
Public Sub btnTest_Click()
  MatrixMulVector(mMatrix, [1, 2, 0, 4, 3])
End

The result vector with the matrix mMatrix from the above project is: [ 55+8i, 37, 52, 8.4, 30-1i ].

Here is an example in which vectors in the plane can be rotated by 90° using a (rotation) matrix-vector product:

Public Sub Main() 
  Dim Theta As Float = Pi / 2 ' Bogenmaß von 90° als reelle Zahl
  Dim A As Matrix = [[Cos(Theta), -Sin(Theta)], [Sin(Theta), Cos(Theta)]] 
 
'-- A is a so-called rotation matrix
'-- If a vector v is multiplied to A from the right, A rotates the vector by the angle Theta=Pi/2, i.e. 90°
'-- A(v) is the non-commutative matrix-vector product A*v.
 
  Print A([1, 0]) 
  Print A([0, 1]) 
 
End

Chapter & Projects

Download

The website uses a temporary session cookie. This technically necessary cookie is deleted when the browser is closed. You can find information on cookies in our privacy policy.
k29/k29.3/k29.3.3/start.txt · Last modified: 17.02.2024 by emma

Page Tools