Matrix addition

This code shows how to add two matrices of size 3 X 3.


Private Sub MatrixAddition()
Dim strArray As String = ""
'Create three matrices.
Dim M1(3, 3), M2(3, 3), M3(3, 3) As Integer
Dim intValue As Integer = 10
Dim intI, intJ As Integer

'intI represents row and
'intJ represents column of all the matrices.
'The intI in the for loop considers
'all the rows and intJ considers all
'the columns.So row is considered first
'and then the column, while performing
'every operation over matrix.

'Add data in first matrix M1.
'Here the first element is 10 and
'then it is incremented by 10.
For intI = 0 To 2
For intJ = 0 To 2
'Value is saved in each cell of matrix
M1(intI, intJ) = intValue
intValue = intValue + 10
Next
Next
'Add data in second matrix M2.
For intI = 0 To 2
For intJ = 0 To 2
'Value is saved in each cell of matrix
M2(intI, intJ) = intValue
intValue = intValue + 10
Next
Next

'Display the first matrix M1.
For intI = 0 To 2
For intJ = 0 To 2
If strArray.Length = 0 Then
strArray = " " & M1(intI, intJ)
Else
strArray = strArray & " " & M1(intI, intJ)
End If
Next
'New line is added after row is created.
strArray = strArray & vbNewLine
Next
MessageBox.Show("The first matrix is " & vbNewLine & strArray)

'Display the second matrix M2.
strArray = ""
For intI = 0 To 2
For intJ = 0 To 2
If strArray.Length = 0 Then
strArray = " " & M2(intI, intJ)
Else
strArray = strArray & " " & M2(intI, intJ)
End If
Next
'New line is added after row is created.
strArray = strArray & vbNewLine
Next
MessageBox.Show("The second matrix is " & vbNewLine & strArray)

'Third matrix M3 is resultant of the addition of
'two matrices M1 and M2.
For intI = 0 To 2
For intJ = 0 To 2
'The sum is saved in corresponding cell
'of matrix M3.
M3(intI, intJ) = M1(intI, intJ) + M2(intI, intJ)
Next
Next

'Display the third matrix M3.
strArray = ""
For intI = 0 To 2
For intJ = 0 To 2
If strArray.Length = 0 Then
strArray = " " & M3(intI, intJ)
Else
strArray = strArray & " " & M3(intI, intJ)
End If
Next
'New line is added after row is created.
strArray = strArray & vbNewLine
Next
MessageBox.Show("The addition of matrices is " & vbNewLine & strArray)
End Sub


Comments

Author: Narendra Dashpute27 Dec 2009 Member Level: Bronze   Points : 0

Nice piece of code.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: