Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Diagonal Matrix
2.1.
Algorithm
2.2.
Examples:
2.3.
Program in Java
2.4.
Input
2.5.
Output
2.6.
Program in C++
2.7.
Input
2.8.
Output
2.9.
Program in Python
2.10.
Input
2.11.
Output
3.
Program Explanation
4.
Scalar Matrix
4.1.
Algorithm
4.2.
Example
4.3.
Program in Java 
4.4.
Output
4.5.
Program in C++
4.6.
Output
4.7.
Program in Python
4.8.
Output
5.
Frequently Asked Questions
5.1.
What is the method for determining whether a matrix is diagonal?
5.2.
What is the scalar matrix condition?
5.3.
Is it true that all diagonal matrices are scalar?
5.4.
What exactly is a multi-dimensional array?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Check Diagonal Matrix and Scalar Matrix

Author Ayush Mishra
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Programming, like math, is a tremendously enjoyable subject to study. Today, we'll talk about matrix.

matrix is a set of integers organized in columns and rows. A matrix's elements must be contained in brackets or parentheses.

It is a set of numbers arranged in a rectangular or array-like layout in its most basic form. An image, a network, or even a non-physical structure could be used.

We will discuss the two matrix types, Diagonal and Scalar Matrix, and their implementation in a different language with examples.

Must Read, Array Implementation of Queue and  Rabin Karp Algorithm

Diagonal Matrix

A square matrix is a diagonal matrix with all of its principal diagonal members equal to zero. If all of the members of a square matrix except the major diagonal are zero, it is said to be a diagonal matrix.

Algorithm

  1. Begin looping through the matrix's elements.
  2. Check the following for each element:
  3. It's a diagonal element if the row number equals the column number. Check to see if the value isn't zero.
  4. If the row number does not equal the column number, it is not a diagonal element. Verify that the value is zero.
  5. The matrix is not a diagonal matrix if any preceding requirements are untrue and the program returns false.
  6. Otherwise, true is returned, indicating that the matrix is diagonal.

Examples:

Input : 
Matrix[4][0] =  {{2, 0, 0, 0},
             {0, 3, 0, 0},
             {0, 0, 4, 0},
             {0, 0, 0, 5}}
Output : Yes

Mat[4][0] = {{4, 3, 2, 1},
             {0, 5, 0, 0},
             {0, 0, 6, 0},
             {0, 0, 0, 7}}
Output : No

Program in Java

The source code for the Java program that checks whether a matrix is diagonal is here.

Code:

import java.util.Scanner;
 class Diagonal_Matrix {

public static void main(String[] args) {
   Scanner sc=new Scanner(System.in);
int r,c;  //Get size of matrix
r=sc.nextInt();
c=sc.nextInt();
         int matrix[][] =new int[r][c];
//Taking input of the matrix
    for(int i=0;i<r;i++)
    {
        for(int j=0;j<c;j++)
        {
            matrix[i][j]=sc.nextInt();
        }
    }
 //Ensure that none of the Diagonal elements are 0 or not.
    int p=0;
    for(int i=0;i<r;i++)
    {
        for(int j=0;j<c;j++)
        {
        if(i!=j && matrix[i][j]!=0)
        {
            p=1;
            break;
        }
        }
    }
    if(p==1)
     System.out.print("The given matrix isn't a diagonal one.");
    else
     System.out.print("The given matrix is a diagonal one.");

}
}

Input

3 3
1 0 0
0 2 0
0 0 3

Output

The given matrix is a diagonal one.

Program in C++

Here is the source code for a C++ application that tests if a matrix is diagonal.

Code:

#include<iostream>
using namespace std;
int main()
{
    int r,c;
    //Get size of matrix
    cin>>r;
    cin>>c;
    int matrix[r][c];
    //Taking input of the matrix
    int i,j;
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            cin>>matrix[i][j];
        }
    }
    //Ensure that none of the Diagonal elements are 0 or not.
    int p=0;
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
        if(i!=j && matrix[i][j]!=0)
        {
            p=1;
            break;
        }
        }
    }
    if(p==1)
        cout<<"The given matrix isn't a diagonal one.";
    else
        cout<<"The given matrix is a diagonal one.";
}

Input

3 3
2 0 0
0 0 0
3 4 0

Output

The given matrix isn't a diagonal one

Program in Python

The source code for the python program that checks whether a matrix is diagonal is here.

Code:

# Get size of matrix
r=int(input(""))
c=int(input(""))
matrix=[]
# Taking input of the 1st matrix
for i in range(r):
    matrix.append([int(j) for j in input().split()])

# check except Diagonal elements are 0 or not

p=0
for i in range(len(matrix)):
    for j in range(len(matrix[0])):
        # check for diagonals element
        if i!=j and matrix[i][j]!=0:
            p=1
            break
if p==1:
    print("Given Matrix is not a diagonal Matrix.")
else:
    print("Given Matrix is a diagonal Matrix.")

Input

3
3
7 0 0
0 8 0
0 0 9

Output

Given Matrix is a diagonal Matrix.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Program Explanation

1. The number of rows and columns must be entered by the user.

2. If not, the elements are instructed to input and save data in the matrix.

3. The matrix's diagonal members are examined. If they're both 0, a temporary variable called 'p' is set to 1.

4. If none of the non-diagonal components are 0, p is given a value of 1.

5. If the flag is set to 1, the inputted array is not a diagonal matrix; otherwise, it is.

6. Finally, the result is printed.

Scalar Matrix

A scalar matrix is a square matrix. If all of the major diagonal elements are equal and all other members except the main diagonal are zero. The identity matrix is expressed as n * I, where n is any real number, and I is the scalar matrix.

Algorithm

There are two sections to the algorithm.

First Part

The criterion for the diagonal elements is checked in the first portion. We compare each diagonal element to the following diagonal element to see if they are equivalent. The matrix is not a scalar matrix if the elements are not equal.

Second Part

The condition of non-diagonal items is checked in the second portion. All non-diagonal elements must have a value of zero. The matrix is not a scalar matrix if any non-diagonal entries are not zero.

Example

Input :
Matrix[3][3] = {{3, 0, 0},
             {0, 3, 0},
             {0, 0, 3}} 
Output : Yes


Matrix[4][4] = {{5, 0, 0, 0},
             {0, 3, 0, 0},
             {0, 0, 1, 0},
             {0, 0, 0, 4}} 
Output : No

Program in Java 

The source code for the Java program that checks whether a matrix is a scalar is here.Both sections of the code have been combined into a Scalar_Matrix function, which returns a boolean result after determining whether or not the input matrix is scalar.

Code:

import java.util.*;
Class Scalar_matrix {

static int N = 4;

static boolean Scalar_Matrix(int matrix[][])
{
 //Check whether or not all elements, except the significant diagonal, are zero.               
for (int i = 0; i < N; i++)
	for (int j = 0; j < N; j++)
		if ((i != j) && (matrix[i][j] != 0))
			return false;

//Check to see if all diagonal elements are the same.
for (int i = 0; i < N - 1; i++)
		if (matrix[i][i] != matrix[i + 1][i + 1])
			return false;
return true;
}
public static void main(String args[])
{
int matrix[ ][ ] = { { 1, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 1 } };
if (Scalar_Matrix(matrix))
	System.out.println("YES");
else
	System.out.println("NO");
}
}

Output

YES

Program in C++

Both sections of the code have been combined into a Scalar_Matrix function, which returns a boolean result after determining whether or not the input matrix is scalar.

Here is the source code for a C++ application that tests if a matrix is scalar.

Code:


#include <bits/stdc++.h>
#define N 4
using namespace std;
bool Scalar_Matrix(int matrix[N][N])
{
//Check whether or not all elements, except the major diagonal, are zero.    
for (int i = 0; i < N; i++)
	for (int j = 0; j < N; j++)
		if ((i != j) && (matrix[i][j] != 0))
			return false;
//Ensure that none of the Diagonal elements are 0 or not.
for (int i = 0; i < N - 1; i++)
	if (matrix[i][i] != matrix[i + 1][i + 1])
			return false;
return true;
}
int main()
{
int matrix[N][N] = { { 7, 0, 0, 0 },
{ 0, 7, 0, 0 },
{ 0, 0, 7, 0 },
{ 0, 0, 0, 7 } };

if (Scalar_Matrix(matrix))
	cout << "YES" << endl;
else
	cout << "NO" << endl;
return 0;
}

Output

YES

Program in Python

The source code for the python program that checks whether a matrix is a scalar is here.

Both sections of the code have been combined into a Scalar_Matrix function, which returns a boolean result after determining whether or not the input matrix is scalar.

Code:

N = 4
def Scalar_Matrix(mat) :
for i in range(0,N) :
for j in range(0,N) :
if ((i != j) and (matrix[i][j] != 0)) :
	return False

# Check whether all diagonal elements are the same or not.
  for i in range(0,N-1) :
if (matrix[i][i] != matrix[i + 1][i + 1]) :
	return False
return True

matrix = [[ 6, 0, 0, 0 ],
[ 0, 6, 0, 0 ],
[ 0, 0, 6, 0 ],
[ 0, 0, 0, 6 ]]

if (Scalar_Matrix(matrix)):
	print("YES")
else :
	print("NO")

Output

YES

Frequently Asked Questions

What is the method for determining whether a matrix is diagonal?

All entries above and below the main diagonal must be zero for a matrix to be diagonal. The main diagonal can have any amount of zero items.

What is the scalar matrix condition?

A square matrix with the feature that its leading diagonal consists exclusively of a specified scalar while all other entries are 0 is considered a scalar matrix.

Is it true that all diagonal matrices are scalar?

A scalar matrix is a square matrix in which all diagonal components are equal to the same scalar, and all other members are zero.

What exactly is a multi-dimensional array?

An array with more than one dimension is known as a multi-dimensional array. It's an array of arrays or an array with several layers.

Conclusion

In this blog, we have discussed the diagonal and scalar matrix problems. We introduced the scalar and diagonal matrix and then the matrix program in different languages.

We hope this blog has improved your understanding of diagonal and scalar matrix programs.

Check out this problem - Matrix Median

Learning never ends, so head over to our practice site Coding Ninjas Studio and practice top problems, take Mock Tests, practice additional SQL questions here, and read educational articles and interview experiences to learn more and become more proficient. Please upvote our blog to assist other ninjas in their development.

Happy Learning!

Previous article
Check if all rows of a matrix are circular rotations of each other
Next article
Diagonally Dominant Matrix
Live masterclass