Basic Matrix Operations in C
Matrix is one of the important mathematical concepts. It has rows and columns. Th structure is given below.
For eg, 2x2 means 2 rows and 2 columns
1 2
3 4
Here, each element is represented in aij format.
The operations in C is given below….
- Addition, Subtraction, Multiplication and Transpose
Program implementation:
#include <stdio.h>
#define M_SIZE 3 //
Set the size as 3
void input_Matrix(int mat1[M_SIZE][M_SIZE], const char
*name) {
printf("Enter
the elements of %s (%dx%d):\n", name, M_SIZE, M_SIZE);
for (int i = 0; i
< M_SIZE; i++)
for (int j =
0; j < M_SIZE; j++) {
printf("%s[%d][%d]: ", name, i, j);
scanf("%d", &mat1[i][j]);
}
}
void print_Matrix(int mat1[M_SIZE][M_SIZE], const char
*m_label) {
printf("\n%s:\n", m_label);
for (int i = 0; i
< M_SIZE; i++) {
for (int j =
0; j < M_SIZE; j++)
printf("%4d", mat1[i][j]);
printf("\n");
}
}
void add_Matrices(int a[M_SIZE][M_SIZE], int
b[M_SIZE][M_SIZE], int result1[M_SIZE][M_SIZE]) {
for (int i = 0; i
< M_SIZE; i++)
for (int j =
0; j < M_SIZE; j++)
result1[i][j] = a[i][j] + b[i][j];
}
void subtract_Matrices(int a[M_SIZE][M_SIZE], int
b[M_SIZE][M_SIZE], int result1[M_SIZE][M_SIZE]) {
for (int i = 0; i
< M_SIZE; i++)
for (int j =
0; j < M_SIZE; j++)
result1[i][j] = a[i][j] - b[i][j];
}
void multiply_Matrices(int a[M_SIZE][M_SIZE], int
b[M_SIZE][M_SIZE], int result1[M_SIZE][M_SIZE]) {
for (int i = 0; i
< M_SIZE; i++)
for (int j =
0; j < M_SIZE; j++) {
result1[i][j] = 0;
for (int k
= 0; k < M_SIZE; k++)
result1[i][j] += a[i][k] * b[k][j];
}
}
void transpose_Matrix(int mat[M_SIZE][M_SIZE], int
result1[M_SIZE][M_SIZE]) {
for (int i = 0; i
< M_SIZE; i++)
for (int j =
0; j < M_SIZE; j++)
result1[j][i] = mat[i][j];
}
int main() {
int
A[M_SIZE][M_SIZE], B[M_SIZE][M_SIZE];
int
result[M_SIZE][M_SIZE];
input_Matrix(A,
"Matrix A");
input_Matrix(B,
"Matrix B");
print_Matrix(A,
"Matrix A");
print_Matrix(B,
"Matrix B");
add_Matrices(A, B,
result);
print_Matrix(result, "Addition");
subtract_Matrices(A, B, result);
print_Matrix(result, "Subtraction");
multiply_Matrices(A, B, result);
print_Matrix(result, "Multiplication");
transpose_Matrix(A, result);
print_Matrix(result, "Transpose");
return 0;
}
Output:
Enter the elements of Matrix A (3x3):
Matrix A[0][0]: 1
Matrix A[0][1]: 2
Matrix A[0][2]: 3
Matrix A[1][0]: 4
Matrix A[1][1]: 5
Matrix A[1][2]: 6
Matrix A[2][0]: 7
Matrix A[2][1]: 8
Matrix A[2][2]: 9
Enter the elements of Matrix B (3x3):
Matrix B[0][0]: 9
Matrix B[0][1]: 8
Matrix B[0][2]:
7
Matrix B[1][0]: 6
Matrix B[1][1]: 5
Matrix B[1][2]: 4
Matrix B[2][0]: 3
Matrix B[2][1]: 2
Matrix B[2][2]: 1
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
9 8 7
6 5 4
3 2 1
Addition:
10 10 10
10 10 10
10 10 10
Subtraction:
-8 -6 -4
-2 0 2
4 6 8
Multiplication:
30 24 18
84 69 54
138 114 90
Transpose:
1 4 7
2 5 8
3 6 9
Yes. The code is executed successfully. Hope, this code
helps you to know about matrix and its operations. Keep coding!!!
Comments
Post a Comment