Como adicionar e subtrair duas matrizes em C ++, Python e JavaScript
Uma matriz é uma matriz retangular de números, símbolos ou expressões organizadas em linhas e colunas. Essa grade retangular de números é comumente usada em matemática, engenharia elétrica e ciência da computação. As matrizes foram originalmente criadas para descrever o sistema de equações lineares.
Agora, as matrizes são amplamente utilizadas em processamento de imagens, análise genética, big data e programação. A adição e subtração de matrizes são as duas operações de matriz mais comuns. Neste artigo, você aprenderá como adicionar e subtrair duas matrizes.
Regras para adição de matriz
Siga estas regras para adicionar duas matrizes:
- Duas matrizes só podem ser adicionadas se forem da mesma ordem.
- Se as duas matrizes são da mesma ordem, adicione os elementos correspondentes das duas matrizes, ou seja, adicione os elementos que têm as mesmas posições.
![](https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2021/05/Add-two-matrices.png)
No exemplo 1, as matrizes podem ser adicionadas porque têm a mesma ordem. No exemplo 2, as matrizes não podem ser adicionadas porque não têm a mesma ordem.
Programa C ++ para adicionar duas matrizes
Abaixo está o programa C ++ para adicionar duas matrizes:
// C++ program for addition of two matrices
#include <bits/stdc++.h>
using namespace std;
// The order of the matrix is 3 x 3
#define size1 3
#define size2 3
// Function to add matrices mat1[][] & mat2[][],
// and store the result in matrix result[][]
void addMatrices(int mat1[][size2], int mat2[][size2], int result[][size2])
{
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
// Driver code
int main()
{
// 1st Matrix
int mat1[size1][size2] = { {9, 8, 7},
{6, 8, 0},
{5, 9, 2} };
// 2nd Matrix
int mat2[size1][size2] = { {4, 7, 6},
{8, 8, 2},
{7, 3, 5} };
// Matrix to store the result
int result[size1][size2];
// Calling the addMatrices() function
addMatrices(mat1, mat2, result);
cout << "mat1 + mat2 = " << endl;
// Printing the sum of the 2 matrices
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
cout << result[i][j] << " ";
}
cout << endl;
}
return 0;
}
Resultado:
mat1 + mat2 =
13 15 13
14 16 2
12 12 7
Programa Python para adicionar duas matrizes
Abaixo está o programa Python para adicionar duas matrizes:
# Python program for addition of two matrices
# The order of the matrix is 3 x 3
size1 = 3
size2 = 3
# Function to add matrices mat1[][] & mat2[][],
# and store the result in matrix result[][]
def addMatrices(mat1,mat2,result):
for i in range(size1):
for j in range(size2):
result[i][j] = mat1[i][j] + mat2[i][j]
# driver code
# 1st Matrix
mat1 = [ [9, 8, 7],
[6, 8, 0],
[5, 9, 2] ]
# 2nd Matrix
mat2 = [ [4, 7, 6],
[8, 8, 2],
[7, 3, 5] ]
# Matrix to store the result
result = mat1[:][:]
# Calling the addMatrices function
addMatrices(mat1, mat2, result)
# Printing the sum of the 2 matrices
print("mat1 + mat2 = ")
for i in range(size1):
for j in range(size2):
print(result[i][j], " ", end='')
print()
Resultado:
mat1 + mat2 =
13 15 13
14 16 2
12 12 7
Programa C para adicionar duas matrizes
Abaixo está o programa C para adicionar duas matrizes:
// C program for addition of two matrices
#include <stdio.h>
// The order of the matrix is 3 x 3
#define size1 3
#define size2 3
// Function to add matrices mat1[][] & mat2[][],
// and store the result in matrix result[][]
void addMatrices(int mat1[][size2], int mat2[][size2], int result[][size2])
{
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
// Driver code
int main()
{
// 1st Matrix
int mat1[size1][size2] = { {9, 8, 7},
{6, 8, 0},
{5, 9, 2} };
// 2nd Matrix
int mat2[size1][size2] = { {4, 7, 6},
{8, 8, 2},
{7, 3, 5} };
// Matrix to store the result
int result[size1][size2];
// Calling the addMatrices function
addMatrices(mat1, mat2, result);
printf("mat1 + mat2 = n");
// Printing the sum of the 2 matrices
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
printf("%d ", result[i][j]);
}
printf("n");
}
return 0;
}
Resultado:
mat1 + mat2 =
13 15 13
14 16 2
12 12 7
Programa JavaScript para adicionar duas matrizes
Abaixo está o programa JavaScript para adicionar duas matrizes:
<script>
// JavaScript program for addition of two matrices
// The order of the matrix is 3 x 3
let size1 = 3;
let size2 = 3;
// Function to add matrices mat1[][] & mat2[][],
// and store the result in matrix result[][]
function addMatrices(mat1, mat2, result) {
for (let i = 0; i < size1; i++) {
for (let j = 0; j < size2; j++) {
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}
// Driver code
// 1st Matrix
mat1 = [ [9, 8, 7],
[6, 8, 0],
[5, 9, 2] ]
// 2nd Matrix
mat2 = [ [4, 7, 6],
[8, 8, 2],
[7, 3, 5] ]
// Matrix to store the result
let result = new Array(size1);
for (let k = 0; k < size1; k++) {
result[k] = new Array(size2);
}
// Calling the addMatrices function
addMatrices(mat1, mat2, result);
document.write("mat1 + mat2 = <br>")
// Printing the sum of the 2 matrices
for (let i = 0; i < size1; i++) {
for (let j = 0; j < size2; j++) {
document.write(result[i][j] + " ");
}
document.write("<br>");
}
</script>
Resultado:
mat1 + mat2 =
13 15 13
14 16 2
12 12 7
Regras para subtração de matriz
Siga estas regras para subtrair duas matrizes:
- Duas matrizes podem ser subtraídas apenas se forem da mesma ordem.
- Se as duas matrizes são da mesma ordem, subtraia os elementos correspondentes das duas matrizes, ou seja, subtraia os elementos que têm as mesmas posições.
![](https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2021/06/Subtract-two-matrices.png)
No exemplo 1, as matrizes podem ser subtraídas porque têm a mesma ordem. No exemplo 2, as matrizes não podem ser subtraídas porque não têm a mesma ordem.
Programa C ++ para subtrair duas matrizes
Abaixo está o programa C ++ para subtrair duas matrizes:
// C++ program for subtraction of two matrices
#include <bits/stdc++.h>
using namespace std;
// The order of the matrix is 3 x 3
#define size1 3
#define size2 3
// Function to subtract matrices mat1[][] & mat2[][],
// and store the result in matrix result[][]
void subtractMatrices(int mat1[][size2], int mat2[][size2], int result[][size2])
{
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
result[i][j] = mat1[i][j] - mat2[i][j];
}
}
}
// Driver code
int main()
{
// 1st Matrix
int mat1[size1][size2] = { {9, 8, 7},
{6, 8, 0},
{5, 9, 2} };
// 2nd Matrix
int mat2[size1][size2] = { {4, 7, 6},
{8, 8, 2},
{7, 3, 5} };
// Matrix to store the result
int result[size1][size2];
// Calling the subtractMatrices() function
subtractMatrices(mat1, mat2, result);
cout << "mat1 - mat2 = " << endl;
// Printing the difference of the 2 matrices (mat1 - mat2)
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
cout << result[i][j] << " ";
}
cout << endl;
}
return 0;
}
Resultado:
mat1 - mat2 =
5 1 1
-2 0 -2
-2 6 -3
Programa Python para subtrair duas matrizes
Abaixo está o programa Python para subtrair duas matrizes:
# Python program for subtraction of two matrices
# The order of the matrix is 3 x 3
size1 = 3
size2 = 3
# Function to subtract matrices mat1[][] & mat2[][],
# and store the result in matrix result[][]
def subtractMatrices(mat1,mat2,result):
for i in range(size1):
for j in range(size2):
result[i][j] = mat1[i][j] - mat2[i][j]
# driver code
# 1st Matrix
mat1 = [ [9, 8, 7],
[6, 8, 0],
[5, 9, 2] ]
# 2nd Matrix
mat2 = [ [4, 7, 6],
[8, 8, 2],
[7, 3, 5] ]
# Matrix to store the result
result = mat1[:][:]
# Calling the subtractMatrices function
subtractMatrices(mat1, mat2, result)
# Printing the difference of the 2 matrices (mat1 - mat2)
print("mat1 - mat2 = ")
for i in range(size1):
for j in range(size2):
print(result[i][j], " ", end='')
print()
Resultado:
mat1 - mat2 =
5 1 1
-2 0 -2
-2 6 -3
Programa C para subtrair duas matrizes
Abaixo está o programa C para subtrair duas matrizes:
// C program for subtraction of two matrices
#include <stdio.h>
// The order of the matrix is 3 x 3
#define size1 3
#define size2 3
// Function to subtract matrices mat1[][] & mat2[][],
// and store the result in matrix result[][]
void subtractMatrices(int mat1[][size2], int mat2[][size2], int result[][size2])
{
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
result[i][j] = mat1[i][j] - mat2[i][j];
}
}
}
// Driver code
int main()
{
// 1st Matrix
int mat1[size1][size2] = { {9, 8, 7},
{6, 8, 0},
{5, 9, 2} };
// 2nd Matrix
int mat2[size1][size2] = { {4, 7, 6},
{8, 8, 2},
{7, 3, 5} };
// Matrix to store the result
int result[size1][size2];
// Calling the subtractMatrices() function
subtractMatrices(mat1, mat2, result);
printf("mat1 - mat2 = n");
// Printing the difference of the 2 matrices (mat1 - mat2)
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
printf("%d ", result[i][j]);
}
printf("n");
}
return 0;
}
Resultado:
mat1 - mat2 =
5 1 1
-2 0 -2
-2 6 -3
Programa JavaScript para subtrair duas matrizes
Abaixo está o programa JavaScript para subtrair duas matrizes:
<script>
// JavaScript program for subtraction of two matrices
// The order of the matrix is 3 x 3
let size1 = 3;
let size2 = 3;
// Function to subtract matrices mat1[][] & mat2[][],
// and store the result in matrix result[][]
function subtractMatrices(mat1, mat2, result) {
for (let i = 0; i < size1; i++) {
for (let j = 0; j < size2; j++) {
result[i][j] = mat1[i][j] - mat2[i][j];
}
}
}
// Driver code
// 1st Matrix
mat1 = [ [9, 8, 7],
[6, 8, 0],
[5, 9, 2] ]
// 2nd Matrix
mat2 = [ [4, 7, 6],
[8, 8, 2],
[7, 3, 5]]
// Matrix to store the result
let result = new Array(size1);
for (let k = 0; k < size1; k++) {
result[k] = new Array(size2);
}
// Calling the subtractMatrices function
subtractMatrices(mat1, mat2, result);
document.write("mat1 - mat2 = <br>")
// Printing the difference of the 2 matrices (mat1 - mat2)
for (let i = 0; i < size1; i++) {
for (let j = 0; j < size2; j++) {
document.write(result[i][j] + " ");
}
document.write("<br>");
}
</script>
Resultado:
mat1 - mat2 =
5 1 1
-2 0 -2
-2 6 -3
Se você quiser dar uma olhada no código-fonte completo usado neste artigo, aqui está o repositório GitHub .
Aumente sua capacidade de programação
Você pode aumentar sua capacidade de programação praticando uma variedade de problemas de programação. Resolver esses problemas de programação ajuda a desenvolver princípios básicos de programação. Eles são essenciais se você deseja se tornar um programador eficiente.