How to check if a given matrix is a scalar matrix
What is a scalar matrix?
The scalar matrix is a square matrix in which every element of the primary diagonal has a constant value and all other elements are equal to zero.
Examples
| Dimension | Matrix |
|---|---|
| 2 x 2 | [[34, 0], [0, 34]] |
| 3 x 3 | [[4, 0, 0], [0, 4, 0], [0, 0, 4]] |
Algorithm
The algorithm has two parts.
First part
In the first part, we check the condition for the diagonal elements. For every diagonal element, we check whether it’s equal to the next diagonal element. If the elements are not equal, then the matrix is not a scalar matrix.
The pseudo-code is as follows.
for i = 0 to numCols - 1
do
if mat[i][i] != mat[i + 1][i + 1] then
return false
done
Second part
In the second part, we check the condition for the non-diagonal elements. All the non-diagonal elements have to be zero. If any one of the non-diagonal elements is not zero, then the matrix is not a scalar matrix.
The pseudo-code is as follows.
for i = 0 to i < numRows
do
for j = 0 to j < numCols
do
if i != j && mat[i][j] != 0 then
return false
done
done
Example
In the example below you can see both parts merged into a checkScalarMatrix function which returns a boolean value after verifying whether the input matrix is scalar or not.
import java.util.Arrays;public class Main {private static void printMatrix(int[][] matrix){for(int[] row: matrix){System.out.println(Arrays.toString(row));}}private static boolean checkScalarMatrix(int[][] matrix){for(int i=0;i<matrix.length-1;i++)if(matrix[i][i] != matrix[i+1][i+1]) return false;for(int i=0; i<matrix.length;i++)for(int j=0; j<matrix[i].length;j++){if(i != j && matrix[i][j] != 0) return false;}return true;}private static void wrapper(int[][] matrix){printMatrix(matrix);if(checkScalarMatrix(matrix)) System.out.println("The matrix is a scalar matrix");else System.out.println("The matrix is not a scalar matrix");}public static void main(String[] args){int[][] matrix = {{4, 0},{0, 4}};wrapper(matrix);System.out.println("-------------");int[][] matrix1 = {{4, 0},{0, -4}};wrapper(matrix1);System.out.println("-------------");int[][] matrix2 = {{4, 3},{0, 4}};wrapper(matrix2);}}
Free Resources
- undefined by undefined