How to check if a matrix is an identity matrix (1 on the main diagonal and 0 elsewhere) in VB.NET

1 Answer

0 votes
Imports System

Public Class Program
	Public Shared Sub Main()
        Dim m As Integer(,) = {
        	{1, 0, 0},
        	{0, 1, 0},
        	{0, 0, 1}}
        Dim rows As Integer = m.GetLength(0)
        Dim cols As Integer = m.GetLength(1)
        Dim flag As Boolean = True

        If rows <> cols Then
            Console.Write("Not a square matrix")
        Else

            For i As Integer = 0 To rows - 1
                For j As Integer = 0 To cols - 1
                    If i = j AndAlso m(i, j) <> 1 Then
                        flag = False
                        Exit For
                    End If

                    If i <> j AndAlso m(i, j) <> 0 Then
                        flag = False
                        Exit For
                    End If
                Next
            Next

            If flag Then
                Console.Write("Identity matrix")
            Else
                Console.Write("Not an identity matrix")
            End If
        End If
    End Sub
End Class




' run:
'
' Identity matrix
'

 



answered Aug 26, 2021 by avibootz
...