Как проверить идентичность двух матриц при программировании
Две матрицы называются идентичными, если обе имеют одинаковое количество строк, столбцов и одинаковых соответствующих элементов. В этой статье вы узнаете, как проверить идентичность двух матриц с помощью Python, C ++, JavaScript и C.
Постановка задачи
Вам даны две матрицы: mat1 [] [] и mat2 [] [] . Вам необходимо проверить идентичность двух матриц. Если две матрицы идентичны, выведите «Да, матрицы идентичны». А если две матрицы не идентичны, выведите «Нет, матрицы не идентичны».
Примеры :
![](https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2021/07/Check-if-2-matrices-are-identical.png)
Условие идентичности двух матриц
Две матрицы называются идентичными тогда и только тогда, когда они удовлетворяют следующим условиям:
- Обе матрицы имеют одинаковое количество строк и столбцов.
- Обе матрицы имеют одинаковые соответствующие элементы.
Подход к проверке идентичности двух заданных матриц
Вы можете следовать приведенному ниже подходу, чтобы проверить, идентичны ли две заданные матрицы или нет:
- Запустите вложенный цикл для обхода каждого элемента обеих матриц.
- Если какие-либо из соответствующих элементов двух матриц не равны, верните false.
- И если до конца цикла не обнаружено ни одного разнородного элемента, верните true.
Программа на C ++ для проверки идентичности двух заданных матриц
Ниже приведена программа на C ++ для проверки идентичности двух заданных матриц:
// C++ program to check if two matrices are identical
#include <bits/stdc++.h>
using namespace std;
// The order of the matrix is 3 x 4
#define size1 3
#define size2 4
// Function to check if two matrices are identical
bool isIdentical(int mat1[][size2], int mat2[][size2])
{
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
if (mat1[i][j] != mat2[i][j])
{
return false;
}
}
}
return true;
}
// Function to print a matrix
void printMatrix(int mat[][size2])
{
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
cout << mat[i][j] << " ";
}
cout << endl;
}
}
// Driver code
int main()
{
// 1st Matrix
int mat1[size1][size2] = { {2, 2, 2, 2},
{2, 2, 2, 2},
{2, 2, 2, 2} };
cout << "Matrix 1:" << endl;
printMatrix(mat1);
// 2nd Matrix
int mat2[size1][size2] = { {2, 2, 2, 2},
{2, 2, 2, 2},
{2, 2, 2, 2} };
cout << "Matrix 2:" << endl;
printMatrix(mat2);
if(isIdentical(mat1, mat2))
{
cout << "Yes, the matrices are identical" << endl;
}
else
{
cout << "No, the matrices are not identical" << endl;
}
// 3rd Matrix
int mat3[size1][size2] = { {3, 3, 3, 3},
{3, 3, 3, 3},
{3, 3, 3, 3} };
cout << "Matrix 3:" << endl;
printMatrix(mat3);
// 4th Matrix
int mat4[size1][size2] = { {4, 4, 4, 4},
{4, 4, 4, 4},
{4, 4, 4, 4} };
cout << "Matrix 4:" << endl;
printMatrix(mat4);
if(isIdentical(mat3, mat4))
{
cout << "Yes, the matrices are identical" << endl;
}
else
{
cout << "No, the matrices are not identical" << endl;
}
return 0;
}
Выход:
Matrix 1:
2 2 2 2
2 2 2 2
2 2 2 2
Matrix 2:
2 2 2 2
2 2 2 2
2 2 2 2
Yes, the matrices are identical
Matrix 3:
3 3 3 3
3 3 3 3
3 3 3 3
Matrix 4:
4 4 4 4
4 4 4 4
4 4 4 4
No, the matrices are not identical
Программа Python для проверки идентичности двух заданных матриц
Ниже приведена программа Python для проверки идентичности двух заданных матриц:
# Python program to check if two matrices are identical
# The order of the matrix is 3 x 4
size1 = 3
size2 = 4
# Function to check if two matrices are identical
def isIdentical(mat1, mat2):
for i in range(size1):
for j in range(size2):
if (mat1[i][j] != mat2[i][j]):
return False
return True
# Function to print a matrix
def printMatrix(mat):
for i in range(size1):
for j in range(size2):
print(mat[i][j], end=' ')
print()
# Driver code
# 1st Matrix
mat1 = [ [2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2] ]
print("Matrix 1:")
printMatrix(mat1)
# 2nd Matrix
mat2 = [ [2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2] ]
print("Matrix 2:")
printMatrix(mat2)
if (isIdentical(mat1, mat2)):
print("Yes, the matrices are identical")
else:
print("No, the matrices are not identical")
# 3rd Matrix
mat3 = [ [3, 3, 3, 3],
[3, 3, 3, 3],
[3, 3, 3, 3] ]
print("Matrix 3:")
printMatrix(mat3)
# 4th Matrix
mat4 = [ [4, 4, 4, 4],
[4, 4, 4, 4],
[4, 4, 4, 4] ]
print("Matrix 4:")
printMatrix(mat4)
if (isIdentical(mat3, mat4)):
print("Yes, the matrices are identical")
else:
print("No, the matrices are not identical")
Выход:
Matrix 1:
2 2 2 2
2 2 2 2
2 2 2 2
Matrix 2:
2 2 2 2
2 2 2 2
2 2 2 2
Yes, the matrices are identical
Matrix 3:
3 3 3 3
3 3 3 3
3 3 3 3
Matrix 4:
4 4 4 4
4 4 4 4
4 4 4 4
No, the matrices are not identical
Программа на JavaScript для проверки идентичности двух заданных матриц
Ниже приведена программа на JavaScript, чтобы проверить, идентичны ли две заданные матрицы или нет:
// JavaScript program to check if two matrices are identical
// The order of the matrix is 3 x 4
var size1 = 3;
var size2 = 4;
// Function to check if two matrices are identical
function isIdentical(mat1, mat2) {
for (let i = 0; i < size1; i++)
{
for (let j = 0; j < size2; j++)
{
if (mat1[i][j] != mat2[i][j])
{
return false;
}
}
}
return true;
}
// Function to print a matrix
function printMatrix(mat) {
for (let i = 0; i < size1; i++) {
for (let j = 0; j < size2; j++) {
document.write(mat[i][j] + " ");
}
document.write("<br>");
}
}
// Driver code
// 1st Matrix
var mat1 = [ [2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2] ];
document.write("Matrix 1:" + "<br>");
printMatrix(mat1);
// 2nd Matrix
var mat2 = [ [2, 2, 2, 2],
[2, 2, 2, 2],
[2, 2, 2, 2] ];
document.write("Matrix 2:" + "<br>");
printMatrix(mat2);
if (isIdentical(mat1, mat2)) {
document.write("Yes, the matrices are identical" + "<br>");
} else{
document.write("No, the matrices are not identical" + "<br>");
}
// 3rd Matrix
var mat3 = [ [3, 3, 3, 3],
[3, 3, 3, 3],
[3, 3, 3, 3] ];
document.write("Matrix 3:" + "<br>");
printMatrix(mat3);
// 4th Matrix
var mat4 = [ [4, 4, 4, 4],
[4, 4, 4, 4],
[4, 4, 4, 4] ];
document.write("Matrix 4:" + "<br>");
printMatrix(mat4);
if (isIdentical(mat3, mat4)) {
document.write("Yes, the matrices are identical" + "<br>");
} else{
document.write("No, the matrices are not identical" + "<br>");
}
Выход:
Matrix 1:
2 2 2 2
2 2 2 2
2 2 2 2
Matrix 2:
2 2 2 2
2 2 2 2
2 2 2 2
Yes, the matrices are identical
Matrix 3:
3 3 3 3
3 3 3 3
3 3 3 3
Matrix 4:
4 4 4 4
4 4 4 4
4 4 4 4
No, the matrices are not identical
Программа на C для проверки идентичности двух заданных матриц
Ниже приведена программа на языке C для проверки идентичности двух заданных матриц:
// C program to check if two matrices are identical
#include <stdio.h>
#include <stdbool.h>
// The order of the matrix is 3 x 4
#define size1 3
#define size2 4
// Function to check if two matrices are identical
bool isIdentical(int mat1[][size2], int mat2[][size2])
{
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
if (mat1[i][j] != mat2[i][j])
{
return false;
}
}
}
return true;
}
// Function to print a matrix
void printMatrix(int mat[][size2])
{
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
printf("%d ", mat[i][j]);
}
printf("n");
}
}
// Driver code
int main()
{
// 1st Matrix
int mat1[size1][size2] = { {2, 2, 2, 2},
{2, 2, 2, 2},
{2, 2, 2, 2} };
printf("Matrix 1:n");
printMatrix(mat1);
// 2nd Matrix
int mat2[size1][size2] = { {2, 2, 2, 2},
{2, 2, 2, 2},
{2, 2, 2, 2} };
printf("Matrix 2:n");
printMatrix(mat2);
if(isIdentical(mat1, mat2))
{
printf("Yes, the matrices are identical n");
}
else
{
printf("No, the matrices are not identical n");
}
// 3rd Matrix
int mat3[size1][size2] = { {3, 3, 3, 3},
{3, 3, 3, 3},
{3, 3, 3, 3} };
printf("Matrix 3: n");
printMatrix(mat3);
// 4th Matrix
int mat4[size1][size2] = { {4, 4, 4, 4},
{4, 4, 4, 4},
{4, 4, 4, 4} };
printf("Matrix 4: n");
printMatrix(mat4);
if(isIdentical(mat3, mat4))
{
printf("Yes, the matrices are identical n");
}
else
{
printf("No, the matrices are not identical n");
}
return 0;
}
Выход:
Matrix 1:
2 2 2 2
2 2 2 2
2 2 2 2
Matrix 2:
2 2 2 2
2 2 2 2
2 2 2 2
Yes, the matrices are identical
Matrix 3:
3 3 3 3
3 3 3 3
3 3 3 3
Matrix 4:
4 4 4 4
4 4 4 4
4 4 4 4
No, the matrices are not identical
Изучите новый язык программирования
Компьютерные науки развиваются очень быстрыми темпами, и конкуренция в этой области сейчас как никогда высока. Вы должны быть в курсе последних навыков и языков программирования. Независимо от того, являетесь ли вы новичком или опытным программистом, в любом случае вам следует изучить некоторые языки программирования в соответствии с отраслевыми требованиями.