Java教程

Java确定给定矩阵是否为单位矩阵

在此程序中,我们需要检查给定矩阵是否为单位矩阵。
身份矩阵
用于确定给定矩阵是否为单位矩阵的Java程序
如果矩阵是其中对角线主元素为1的方阵,则该矩阵被称为单位矩阵。元素为零。

算法

步骤1: START 步骤2: 定义rows,cols 步骤3: SET flag= true 步骤4: 初始化矩阵 a[][] = {{1,0,0},{0,1,0},{0,0,1}} 步骤5: rows = a.length 步骤6: cols = a[0].length 步骤7: if(rows!= cols) 然后 PRINT"矩阵应为方矩阵" 转到其他步骤8 步骤8: 直到i < rows 重复步骤9至11,//for(i = 0; i < rows; i++) 步骤9: 直到将j < cols ////for(j = 0; j < cols; j++) 重复步骤10至步骤11 步骤10: if(i == j && a [i] [j] == 1) 然后 SET flag= false
break;
步骤11: if(i!= j && a [i] [j]!= 0) SET flag= false break; 步骤12: if(flag)
then PRINT("Given matrix is an identity matrix")
else
PRINT("Given matrix is not an identity matrix")
步骤13: END

程序:

public class IdentityMatrix
{
    public static void main(String[] args) {
        int rows, cols;
        boolean flag = true;
        //Initialize matrix a
        int a[][] = {
            {1, 0, 0},
            {0, 1, 0},
            {0, 0, 1}
        };
        //Calculates the number of rows and columns present in the given matrix
          rows = a.length;
        cols = a[0].length;
        //Checks whether given matrix is a square matrix or not
        if(rows != cols){
            System.out.println("Matrix should be a square matrix");
        }
        else {
            //Checks if diagonal elements are equal to 1 and rest of elements are 0
            for(int i = 0;i <rows;i++){
                for(int j = 0;j <cols;j++){
                    if(i == j && a[i][j] != 1){
                        flag = false;
                        break;
                    }
                    if(i != j &&a[i][j] != 0){
                        flag = false;
                        break;
                    }
                }
            }
            if(flag)
                System.out.println("Given matrix is an identity matrix");
            else
                System.out.println("Given matrix is not an identity matrix");
        }
    }
}
输出:
Given matrix is an identity matrix
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4