MATRIX MULTIPLICATION

 

In this "MATRIX MULTIPLICATION PROGRAM" article, You can learn about matrix multiplication programs, matrix multiplication basics, dimensions, types of matrices, scalar multiplication, dot product, rule of multiplying matrices, algorithm, c and python program, and matrix multiplication program using python numpy.

MATRIX MULTIPLICATION BASICS

A matrix is a rectangular arrangement of numbers into rows and columns. it is also known as a 2-D array. Each cell contains a number and each number in a matrix is referred to as a matrix element or entry.

The dimensions of the matrix tell its size: the number of rows and columns of the matrix, in that order. For example,

MULTIPLYING MATRICES
MULTIPLYING MATRICES

Since Matrix A has one row and three columns, so it's dimension is 1 × 3, pronounced as "1 by 3". Similarly, Matrix B has three rows and two columns, so its dimensions are 3 × 2.

No of rows comes first then no of columns. (Dimension)

Row is treated as row i and column is treated as column j of Matrix A is denoted as Ai,j.

There are different types of matrices,

  • Square Matrix.
  • Symmetric Matrix.
  • Triangular Matrix.
  • Diagonal Matrix.
  • Identity Matrix.
  • Orthogonal Matrix.

SCALAR MULTIPLICATION

The term "SCALAR" means (of a quantity) having only magnitude, not direction. Like, 2, 1, 10 etc real numbers.

The term scalar multiplication refers to the product of a real number and a matrix. In scalar multiplication, each entry in the matrix is multiplied by the given scalar. For example,

Scalar multiplication
Scalar multiplication

Since, A is multiplied with a real number i.e. 3 thus each entry in the matrix is multiplied by 3.

In many cases, the repeated addition of a matrix is done as A+ A+ A = 3 ( A ).

DOT PRODUCT

We are familiar with ordered pairs, for example (2,5), and perhaps even ordered triples, for example (3,1,8).

We can find the dot product of two n-tuples of equal length by summing the products of corresponding entries.

For example, to find the dot product of two ordered pairs, we multiply the first coordinates and the second coordinates and add the results.

DOT PRODUCT
DOT PRODUCT

Ordered n-tuples are often indicated by a variable with an arrow on top. For example, we can let a⃗=(3,1,8) and b⃗=(4,2,3). The expression a⃗⋅b⃗ indicates the dot product of these two ordered triples and can be found as follows:

a⃗⋅b⃗=(3,1,8)⋅(4,2,3)

=3⋅4+1⋅2+8⋅3

=12+2+24

=38

Notice that the dot product of two n-tuples of equal length is always a single real number.

To perform matrix multiplication, at least 2 matrices are required. Thus there are different types of matrices, there are some rules given below, which are used to perform matrix multiplication.

RULE OF MULTIPLYING MATRICES

For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix. The result matrix has the number of rows of the first and the number of columns of the second matrix.

We can add, subtract, multiply, and divide 2 matrices. To do so, we are taking input from the user for row number, column number, first matrix elements, and second matrix elements. Then we are performing multiplication on the matrices entered by the user.

In matrix multiplication, the first matrix one-row element is multiplied by the second matrix all column elements.

The resulting matrix dimension is First matrix row size and second matrix column size.

Matrix Multipllcation
Matrix Multipllcation

ALGORITHM:

Step 1: Start the program
Step 2: Initialize matrices A and B
Step 3: Initialize row and column using initMatrix function
Step 4: If c1!=r2 then exit because rule violate
Step 5: Input matrices A and B values using valueMatrix function
Step 6: Print A and B matrix values using printMatrix function
Step 7: Using MATRIXmutli calculate multiplication value
    Let C be a new matrix of the appropriate size
    For i from 1 to r1:
        For j from 1 to c2:
            Cij = 0
            For k from 1 to c1:
                Set Cij ← Cij + Aik × Bkj
         
    Print C matrix values as result
Step 8: Stop the program

C PROGRAM


#include<stdio.h>
#include<stdlib.h>


void initMatrix( int *r, int *c)
{
	printf("\nNumber of rows: ");
	scanf("%d",r);

	printf("\nNumber of columns: ");
	scanf("%d",c);

}

void valueMatrix(int a[50][50],int r,int c)
{
	for(int i=0; i<r; i++)
	{
		for(int j=0; j<c; j++)
		{
			printf("Array[%d][%d]: ",i+1,j+1);
			scanf("%d",&a[i][j]);
		}
	}
}

void printMartix(int a[50][50], int r, int c)
{
	for(int i=0; i<r; i++)
		{
			for(int j=0; j<c; j++)
			{
				printf(" %d ",a[i][j]);
			}
			printf("\n");
		}	
}

void MATRIXmutli(int a[50][50], int b[50][50], int r1,int r2, int c1, int c2)
{
	int res[50][50];
	for(int i=0; i<r1; i++)
	{
		for(int j=0; j<c2; j++)
		{
			res[i][j]=0;
			for(int k=0; k<c1; k++)
			{
				res[i][j]+=a[i][k]*b[k][j];
			}
		}
	}	
	printMartix(res,r1,c2);	
}

int main()
{

	int a[50][50],b[50][50], mul[50][50],r1,r2,c1,c2;
	r1=c1=r2=c2=0;
	system("clear"); // used in linux based terminal
	// clrscr(); used in windows based terminal
	printf("\n\tFirst Matrix");
	initMatrix(&r1,&c1);	

	printf("\n\tSecond Matrix");
	initMatrix(&r2,&c2);
	
	// matrix multiplication rule
	if(c1!=r2)
		exit(1);

	printf("\n\tFirst Matrix\n");
	valueMatrix(a,r1,c1);

	printf("\n\tSecond Matrix\n");
	valueMatrix(b,r2,c2);

	printf("\n\tFirst Matrix\n");
	printMartix(a,r1,c1);

	printf("\n\tSecond Matrix\n");
	printMartix(b,r2,c2);	


	printf("\n\tResult\n");
	MATRIXmutli(a,b,r1,r2,c1,c2);


return 0;
}
// [ is denoted as left bracket
// < is less than and so on.

PYTHON PROGRAM:


a=[]
b=[]
l=[]

print("\t First Matrix")
r1=int(input("Number of rows: "))
c1=int(input("Number of columns: "))

print("\t Second Matrix")
r2=int(input("Number of rows: "))
c2=int(input("Number of columns: "))

if(c1!=r2):
	exit(1)

#result matrix
r=[[0 for i in range(c2)] for i in range(r1)]	

print("\tFirst Matrix")
for i in range(r1):
	for j in range(c1):
		print("Array[",(i+1),"][",(j+1),"]: ",end="")
		v=int(input())
		l.append(v)
	a.append(l)
	l=[]

print("\tSecond Matrix")
l=[]
for i in range(r2):
	for j in range(c2):
		print("Array[",(i+1),"][",(j+1),"]: ",end="")
		v=int(input())
		l.append(v)
	b.append(l)
	l=[]

print("\tFirst Matrix")
for i in range(len(a)):
	for j in range(len(a[0])):
		print(a[i][j]," ",end=" ")
	print()

print("\tSecond Matrix")
for i in range(len(b)):
	for j in range(len(b[0])):
		print(b[i][j]," ",end=" ")
	print()

for i in range(len(a)): # no of rows in first matrix
    # iterating by coloum by B # no of col in 2nd matrix 
	for j in range(len(b[0])): 
        # iterating by rows of B 
		for k in range(len(b)): 
			r[i][j] += a[i][k] * b[k][j] 

print("\tResult")
for i in range(len(a)):
	for j in range(len(a[0])):
		print(r[i][j]," ",end=" ")
	print()



INPUT OUTPUT:


	First Matrix
Number of rows: 2

Number of columns: 2

	Second Matrix
Number of rows: 2

Number of columns: 2

	First Matrix
Array[1][1]: 2
Array[1][2]: 3
Array[2][1]: 3
Array[2][2]: 4

	Second Matrix
Array[1][1]: 1
Array[1][2]: 2
Array[2][1]: 1
Array[2][2]: 2

	First Matrix
 2  3 
 3  4 

	Second Matrix
 1  2 
 1  2 

	Result
 5  10 
 7  14 

NUMPY IN PYTHON

A Very simple program using numpy in python.

import numpy as np 
a=[[2,3],[3,4]]
b=[[1,2],[1,2]]
r=np.dot(a,b)
for r1 in r:
	print(r1)

#OUTPUT
 5  10 
 7  14 

This program is common in many examinations. Do practice with these programs.

Matrix multiplication program has a simple trick to remember the code, read it as,

for i=0 to Matrix_A_row
   for j=0 to Matrix_B_col
       res=0
        for k=0 to Matrix_A_col
            res of i,j + = a of i,k * b of k,j
print(res,Matrix_A_row, Matrix_B_column)

The given above short note is helpful to you.

YOU MIGHT LIKE:

https://www.shoutcoders.com/divide-and-conquer-quick-sort/

https://www.shoutcoders.com/activity-selection-problem/

https://www.shoutcoders.com/fifo-page-replacement-algorithm/

https://www.shoutcoders.com/memory-management-note/

If you feel any question regarding this, feel free to comment below, and Hope that you can learn something new today. :)

Comments

Popular posts from this blog

C PROGRAMMING NOTE

CONSTRUCTOR & DESTRUCTOR