Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Matrix Multiplication in C – How to Multiply Matrices?

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

Multiplying two matrices is a core operation utilised in various programming languages and fields of mathematics. It is a mathematical operation that is done by multiplying two matrices to result in another matrix.

 

A matrix can be described as a set of numbers arranged in rows and columns with their values used in computation and to represent information. Knowledge of how matrices can be multiplied is important when coding in the C programming language due to several uses in graphics, scientific computations, and in solving certain engineering problems.

 

Matrix multiplication is not just a multiplication in terms of element-wise multiplication. It has some requirements and rules that must be followed for the operation to be completed. In this blog, we will look in detail at these rules and conditions, go through the steps, and show you examples of C language code that enable efficient implementation of matrix multiplication.

Conditions for Matrix Multiplication

However, we must clarify the conditions which are to be met before multiplying two matrices. The first requirement that a transposition requires is that the number of columns in the first matrix should equal the number of rows in the second matrix. This condition makes sure that each component in the row of the first matrix has a matching component in the column of the second matrix.

 

For instance, the multiplication A×B of matrix A (dimensions m×n) and matrix B (dimensions p×q) is only possible if n=p. Matrix C, as a result, will have m×q dimensions.

 

Matrix A (m x n) Matrix B (p x q) Resulting Matrix C (m x q)
2 x 3 3 x 4 2 x 4
4 x 2 2 x 5 4 x 5

Step-by-Step Guide to Matrix Multiplication

Before performing matrix multiplication, one must understand the rules to do so. Let’s walk through it step-by-step:

  1. Initialise the Matrices: The first step is defining the dimensions and initialising the matrices.
  2. Multiply the Matrices: To calculate the value of each entry in the resulting matrix, find the product of the elements in the row of the first matrix with the elements in the column of the second matrix and add all these products.
  3. Store the Results: Save the summations in the corresponding position of the resulting matrix.

Let’s illustrate this with a 2×2 matrix example:

 

Matrix A:

 

1 2
3 4

 

Matrix B:

 

5 6
7 8

 

To multiply these matrices, we calculate each element of the resulting matrix C as follows:

C11= (1×5) + (2×7) = 5+14 = 19 C12= (1×6) + (2×8) = 6+16 = 22 C21= (3×5) +(4×7) = 15+28 = 43 C22= (3×6) + (4×8) = 18+32 = 50

The resulting matrix C is:

19 22
43 50

Implementing Matrix Multiplication in C

When performing matrix multiplication in C, we follow a structured approach. Here’s a simple code example:

#include <stdio.h> int main() { int a[2][2] = {{1, 2}, {3, 4}}; int b[2][2] = {{5, 6}, {7, 8}}; int c[2][2] = {0}; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { c[i][j] += a[i][k] * b[k][j]; } } } printf("Resulting matrix:n"); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { printf("%d ", c[i][j]); } printf("n"); } return 0; }

Output:

Resulting matrix:
19 22
43 50

 

Here, we are declaring matrices a and b of a given size. We then multiply these matrices and store the result in matrix c; the nested for-loops are used to multiply and sum the elements together. Lastly, we print the matrix as the result of the given operation.

Handling User Input for Matrix Dimensions and Elements

To make our program more flexible, we can change it so we can receive user input in terms of matrix dimensions and the elements themselves. This way, we can address matrices of different dimensions.

#include <stdio.h> int main() { int m, n, p, q; printf("Enter dimensions of first matrix (rows and columns): "); scanf("%d %d", &m, &n); printf("Enter dimensions of second matrix (rows and columns): "); scanf("%d %d", &p, &q); if (n != p) { printf("Matrix multiplication not possible. Number of columns in first matrix must equal number of rows in second matrix.n"); return 1; } int a[m][n], b[p][q], c[m][q]; printf("Enter elements of first matrix:n"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { scanf("%d", &a[i][j]); } } printf("Enter elements of second matrix:n"); for (int i = 0; i < p; i++) { for (int j = 0; j < q; j++) { scanf("%d", &b[i][j]); } } for (int i = 0; i < m; i++) { for (int j = 0; j < q; j++) { c[i][j] = 0; for (int k = 0; k < n; k++) { c[i][j] += a[i][k] * b[k][j]; } } } printf("Resulting matrix:n"); for (int i = 0; i < m; i++) { for (int j = 0; j < q; j++) { printf("%d ", c[i][j]); } printf("n"); } return 0; }

Output:

Enter dimensions of the first matrix (rows and columns): 2 and 3

 

Enter dimensions of the second matrix (rows and columns): 3 and 2

 

Enter elements of the first matrix:

 

1 2 3
4 5 6

 

Enter elements of the second matrix:

 

7 8
9 10
11 12

 

Resulting matrix:

 

58 64
139 154

 

In this version of the code, the user is asked to input the dimensions and elements of the matrices. We then verify if the multiplication is feasible given the dimensions of the inputs. If the conditions are met, we will carry out the multiplication and show the answer to the user.

 

Processing input from the user allows our program to be generalised for various situations. It allows us to extend the matrices of any dimensions and orientations and offers a solid solution for matrix operations in C.

Working with Square and Rectangular Matrices

In the multiplication of matrices in C, it is important to know the difference between square and rectangular matrices. Each type has its own regulations that apply to the multiplication process.

 

Square Matrices

 

A square matrix is always formed by an equal number of rows and columns in it or the matrix is symmetrical. These matrices are easy to manipulate. When two square matrices are multiplied by each other, the element of the resultant matrix is the sum of the products of each element of the row of the first and the column of the second one.

Consider two 3×3 matrices, A and B:

 

Matrix A:

 

1 2 3
4 5 6
7 8 9

Matrix B:

 

9 8 7
6 5 4
3 2 1

 

The resulting matrix C is calculated as follows:

C11= (1×9) + (2×6) + (3×3) = 9+12+9 = 30

C12= (1×8) + (2×5) + (3×2) = 8+10+6 = 24

And so on for all elements.

Matrix C:

30 24 18
84 69 54
138 114 90

 

Rectangular Matrices

A rectangular matrix is a type of matrix that has a distinct number of rows and columns. As for the multiplication rules, they stay the same, whereas the dimensions require more attention. The key condition remains: the number of columns in the first matrix should equal the number of rows in the second matrix.

 

Consider matrix A with dimensions 2×3 and matrix B with dimensions 3×2:

Matrix A:

1 2 3
4 5 6

 

Matrix B:

7 8
9 10
11 12

 

The resulting matrix C will have dimensions 2×2:

C11= (1×7) + (2×9) + (3×11) =7+18+33 = 58

C12= (1×8) + (2×10) + (3×12) = 8+20+36 = 64

And so on

Matrix C:

58 64
139 154
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Optimising Matrix Multiplication Code Using Functions

When it comes to coding for matrix multiplication, different matrix sizes may require long and even repetitive code. Using functions can lighten the work, besides making the code more segmented and thus making it easier to debug.

We can create three main functions:

  1. Input Function:
    • This function asks the user for the elements of the matrix.
  2. Display Function:
    • This function displays any given Matrix.
  3. Multiply Function:
    • This function calculates the product and stores the result in the result matrix.

Here’s an example of how we can structure our code:

#include <stdio.h> void inputMatrix(int rows, int cols, int matrix[rows][cols]) { printf("Enter elements of the matrix:n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { scanf("%d", &matrix[i][j]); } } } void displayMatrix(int rows, int cols, int matrix[rows][cols]) { printf("Matrix:n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%d ", matrix[i][j]); } printf("n"); } } void multiplyMatrices(int m, int n, int p, int q, int a[m][n], int b[p][q], int result[m][q]) { for (int i = 0; i < m; i++) { for (int j = 0; j < q; j++) { result[i][j] = 0; for (int k = 0; k < n; k++) { result[i][j] += a[i][k] * b[k][j]; } } } } int main() { int m, n, p, q; printf("Enter dimensions of first matrix (rows and columns): "); scanf("%d %d", &m, &n); printf("Enter dimensions of second matrix (rows and columns): "); scanf("%d %d", &p, &q); if (n != p) { printf("Matrix multiplication not possible. Number of columns in first matrix must equal number of rows in second matrix.n"); return 1; } int a[m][n], b[p][q], result[m][q]; inputMatrix(m, n, a); inputMatrix(p, q, b); multiplyMatrices(m, n, p, q, a, b, result); printf("Resulting matrix:n"); displayMatrix(m, q, result); return 0; }

Output

Enter dimensions of the first matrix (rows and columns): 2 and 3

Enter dimensions of the second matrix (rows and columns): 3 and 2

Enter elements of the matrix:

1 2 3
4 5 6

Enter elements of the matrix:

7 8
9 10
11 12

Resulting matrix:

Matrix:

58 64
139 154

Common Errors and How to Handle Incompatible Matrices

The process of multiplying matrices can raise particular issues and the handling of incorrect size matrices can be problematic. If you know what kind of mistakes people can make, you can easily resolve the problems the user may have.

Dimension Mismatch

The first and the most popular mistake is a mistake that refers to the fact that the number of columns of the first matrix is not equal to the number of rows of the second matrix. This means that it makes the multiplication impossible.

if (n != p) { printf("Matrix multiplication not possible. Number of columns in the first matrix must equal the number of rows in the second matrix.n"); return 1; }

This check ensures we only proceed if the matrices are compatible.

Overflow Errors

With large matrices or for a large number of elements, the resulting values affect the storage facility of the data type. Larger data types such as ‘long’ or ‘long long’ can partially deal with this problem.

Incorrect Indexing

Any mistake in the indexing of rows and columns can result in wrong output values. Make sure that the loop indices are properly correlated with the dimensionality of the matrix.

Algorithm and Flow Chart for Matrix Multiplication

Understanding the algorithm and visualising it with a flow chart can simplify the process. Here’s the algorithm for matrix multiplication:

  1. Start.
  2. Please provide the dimensions of the first matrix – m and n.
  3. After that, input the dimensions of the second matrix, p and q.
  4. If n does not equal p, print an error message and exit the program.
  5. Create matrices of appropriate sizes: a[m][n], b[p][q], and c[m][q] are rectangle matrices.
  6. Input values into matrix a.
  7. Input elements for the second matrix b.
  8. We start by setting all elements in matrix c to zero.
  9. For each element in c, calculate the sum of the products of corresponding elements from a and b.
  10. Print matrix c.
  11. Stop.

Using this algorithm and creating a flow chart that follows it, we make the process of matrix multiplication in C less complicated and less prone to mistakes.

Complexity Analysis of Matrix Multiplication

Comprehending the complicated nature of matrix multiplication facilitates the optimization of our programs. The time complexity of the conventional matrix multiplication algorithm is O(n^3). This indicates that the time needed to multiply the matrices grows cubically with their size.

Time Complexity

The reason for the time complexity of O(n^3) is that we execute many nested loops. We do n^3 multiplications and add for every element in the resultant matrix. This procedure is repeated for every n^2 element, resulting in a total of n^3 operations.

Space Complexity

Multiplication of matrices has an O(n^2) space complexity. The requirement to store the output matrix is the cause of this complexity. Usually needing n^2 space, the size of the output matrix is determined by the dimensions of the input matrices.

Optimising Matrix Multiplication

Using sophisticated algorithms such as Strassen’s method, we can optimise matrix multiplication. By using Strassen’s technique, the time complexity is reduced to O(n^{2.81}). Even while this improvement looks little, for large matrices it can have a big impact.

 

With Strassen’s approach, matrices are divided into submatrices and then multiplied and combined recursively. This method speeds up computations by reducing the amount of multiplications that are required.

Practical Applications of Matrix Multiplication in C

There are various benefits that we can derive from solving matrix multiplication in C. First, it provides mathematical simplification of complicated or large equations that can be easily handled in code. By using C, we take advantage of it by enhancing its feature, which allows it to handle large amounts of data. It has practical uses that are broad and can also make a significant difference in the world.

Graphics and Image Processing

Matrices are commonly used in graphics to transform shapes, scale, rotate, or translate figures. For instance, image rotation can be done by multiplying the coordinates of each pixel by a rotation matrix. This operation is critical in any computer graphics and animation process.

Solving Linear Systems

Quite several problems encountered in engineering and physics require solutions to systems of linear equations. The solutions involve matrix multiplication. That way, matrices help in representing the system of equations and using the multiplication of matrices to come up with an efficient solution.

Data Analysis and Machine Learning

Matrix multiplication is an important operation used in data analysis and machine learning. Techniques such as PCA or linear regression are matrix-based, for example. Thus, by using these operations on large matrices or vectors in C, it becomes easier to manipulate large sets of data and perform sophisticated calculations.

Conclusion

In this blog, we have taken a tour through what Matrix Multiplication in C entails starting from the basics up to coding them out. This was followed by a discussion of when matrix multiplication is possible and an example of how it can be done. We also learn about the contrast between square and rectangular matrices and our focus on the use of functions to improve the code.

 

The time complexity of matrix multiplication is very high, but with efficient techniques, such as Strassen’s method, an improvement is possible. Their applications in automotive design or electoral maps, physics or chemistry simulations, statistics, and finance reveal their value in different areas.

 

Apart from sharpening our coding skills, understanding matrix multiplication in C enables us to solve more problems in various fields. So keep practising and continue to learn to expand and further develop your knowledge skills.

 

FAQs
When multiplying two matrices the number of columns in the first need to be equal to the number of rows in the second.
When handling incompatible dimensions, you should check the conditions before doing multiplication. If there are columns in the first matrix, and rows in the second matrix are not equal then display an error message and stop the program.
Mathematical operations on matrices are easier to manage and maintain when implemented through functions. There are such things as functions that help to divide different stages of the matrix multiplication process, such as input, display, and proper calculation. It makes the code more readable and easier to debug.
Yes, matrix multiplication is important and useful in solving linear equations. To solve systems of linear equations efficiently, one can convert them to matrices and perform multiplication to find the solution. This technique is widely used in engineering, physics, and data analysis.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved