Matrix Operations

Learn how to perform addition, subtraction, and multiplication using 2D arrays.

Introduction

Matrices in C are represented using 2D arrays. This section covers matrix addition, subtraction, and multiplication along with examples and program structures.

What is a Matrix?

A matrix is a rectangular arrangement of numbers in rows and columns. In C, it is implemented as int A[rows][cols];

Matrix Addition

Two matrices can be added only if they have the same dimensions.

#include <stdio.h>

int main() {
    int a[2][2] = {{1, 2}, {3, 4}};
    int b[2][2] = {{5, 6}, {7, 8}};
    int sum[2][2];

    for(int i=0; i<2; i++) {
        for(int j=0; j<2; j++)
            sum[i][j] = a[i][j] + b[i][j];
    }

    printf("Sum of Matrix:\\n");
    for(int i=0; i<2; i++) {
        for(int j=0; j<2; j++)
            printf("%d ", sum[i][j]);
        printf("\\n");
    }
}

Matrix Subtraction

for(int i=0; i<2; i++)
    for(int j=0; j<2; j++)
        diff[i][j] = a[i][j] - b[i][j];

Matrix Multiplication

Multiplication is possible only if columns of A = rows of B.

int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int C[2][2];

for(int i=0; i<2; i++) {
    for(int j=0; j<2; j++) {
        C[i][j] = 0;
        for(int k=0; k<2; k++)
            C[i][j] += A[i][k] * B[k][j];
    }
}