matrix in programming - data structures and algorithms
October 8, 2022

Matrix in Programming

Two-dimensional array(Marix) – A two-dimensional array is a list of finite numbers m*n homogeneous data elements such that

  1. the element of the array is referenced by two index sets consisting of m and n consecutive integer numbers.
  2. the elements of the array are stored in consecutive The size of two – a dimensional array is denoted by m*n.

matrix in programming

Types of MATRIX


Diagonal Matrix

1 0 0 0
0 2 0 0
0 0 3 0
0 0 0 4

Tri Diagonal Matrix

1 4 0 0
2 2 4 0
0 2 3 2
0 0 3 4

Lower Triangular Matrix

1 0 0 0
1 2 0 0
2 3 3 0
3 4 2 4

Upper Triangular Matrix

1 3 2 1
0 2 4 2
0 0 3 3
0 0 0 4

Sparse Matrix

1 0 0 0
0 0 0 0
0 2 0 0
0 0 0 4

Dense Matrix

1 0 9 1
0 6 8 4
4 2 3 0
0 3 0 4

Unit Matrix

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

Symmetric Matrix

1 2 3 4
2 1 2 3
3 2 1 2
4 3 2 4

NOTE:-we assume that all the matrices (except Sparse and Dense) are square matrices.

MATRIX OPERATION

  1. Sum
  2. Multiply
  3. Transpose
  4. Sorting

SPARSE MATRIX

An m*n matrix is said to be sparse if many of its elements are zero. A matrix that is not sparse is called a dense matrix. In sparse matrix e.g – diagonal matrix, tri diagonal matrix in array representation, an array of triplets of type- < row, col, the element is used to store nonzero elements where the first field of the triplet is used to record row position, second to record column position and the third one to record the nonzero elements of the sparse matrix this row is a header in sparse matrix


Algorithm for Transpose of a sparse matrix

TRANSPOSE (SM1, SM2) 

Here SM1 and SM2 are two sparse matrices. This algorithm computes the transposition of SM1 into SM2. N is no. of nonzero elements. The header row is 0

1. Set MAXROW := SM1 [0,2], MAXCOL := SM1 [0,3], N := SM1 [0,1]
2. Set SM2 [0,1] := N, SM2 [0,2] :MAXCOL, SM2 [0,3] := MAXROW
3. If N > 0, then [If the number of non-zero elements is more than 0]
4.     Set I = 1 [I is a counter for SM2]
5.     Repeat Step 6 for COL:= 1 to MAXCOL  [Counter for counting columns]
6.          Repeat Step (a) for P:= 1 to N  [Counter for SM1]
(a)             If SM1 [P.3] = COL, then
                       (i)     SM2 [I,1] := SM1 [P,1]
                       (ii)    SM2 [I,2] := SM1 [P,3]
                       (iii)   SM2 [I,3] := SM1 [P,2]
                       (iv)   Set I :I +I

                 [End of If structure.]
             [End of Step 6 loop]
         [End of Step 5]
     [End of If structure]
7. Exit.