0% found this document useful (0 votes)
8 views30 pages

Rahul ML File' (1) 2

The document outlines three experiments focused on implementing statistical functions and array manipulations using Python, specifically with NumPy and SciPy libraries. Experiment 1 covers the calculation of Mean, Median, Mode, and Variance, while Experiment 2 introduces N-dimensional arrays, array creation functions, and combining arrays. Experiment 3 discusses converting lists to arrays, indexing, slicing, and reshaping arrays.

Uploaded by

Rahul Jadhaw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views30 pages

Rahul ML File' (1) 2

The document outlines three experiments focused on implementing statistical functions and array manipulations using Python, specifically with NumPy and SciPy libraries. Experiment 1 covers the calculation of Mean, Median, Mode, and Variance, while Experiment 2 introduces N-dimensional arrays, array creation functions, and combining arrays. Experiment 3 discusses converting lists to arrays, indexing, slicing, and reshaping arrays.

Uploaded by

Rahul Jadhaw
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Experiment–1

Aim: Write a Program to implement Mean, Median, Mode and Variance using Python.

Theory:

Mean:

mean() function can be used to calculate mean/average of a given list of numbers. It returns mean of the
data set passed as parameters.

Arithmetic mean is the sum of data divided by the number of data-points. It is a measure of the central
location of data in a set of values which vary in range. In Python, we usually do this by dividing the sum
of given numbers with the count of number present.

Given set of numbers: [n1, n2, n3, n5,

n6] Sum of data-set = (n1 + n2 + n3 + n4

+ n5)Number of data produced = 5

Median:

median() function in the statistics module can be used to calculate median value from an unsorted data-
list. The biggest advantage of using median() function is that the data-list does not need to be sorted
before being sent as parameter to the median() function.

Median is the value that separates the higher half of a data sample or probability distribution from the
lower half. For a dataset, it may be thought of as the middle value. The median is the measure of the
central tendency of the properties of a data-set in statistics and probability theory. For odd set of elements,
the median value is the middle one.

For even set of elements, the median value is the mean of two middle elements.

Mode:

The mode of a set of data values is the value that appears most often. It is the value at which the data is
most likely to be sampled. A mode of a continuous probability distribution is often considered to be any
value x at which its probability density function has a local maximum value, so any peak is a mode.

The mode() function is one of such methods. This function returns the robust measure of a central data
point in a given range of data-sets.

Variance:

variance() function should only be used when variance of a sample needs to be calculated. There’s another
function known as pvariance(), which is used to calculate the variance of an entire population.

In pure statistics, variance is the squared deviation of a variable from its mean. Basically, it measures the
spread of random data in a set from its mean or median value. A low value for variance indicates that the
data are clustered together and are not spread apart widely, whereas a high value would indicate that the
data in the given set are much more spread apart from the average value.

Procedure:

Mean

The mean value is the average value.

To calculate the mean, find the sum of all values, and divide the sum by the number of values:

(99+86+87+88+111+86+103+87+94+78+77+85+86) / 13 = 89.77

Median for odd:

If there are two numbers in the middle, divide the sum of those numbers by two.77,

78, 85, 86, 86, 86, 87, 87, 94, 98, 99, 103

(86 + 87) / 2 = 86.5

Median for even:

The median value is the value in the middle, after you have sorted all the values:

77, 78, 85, 86, 86, 86, 87, 87, 88, 94, 99, 103, 111

Mode:

The Mode value is the value that appears the most number of times:

99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86 = 86

The SciPy module has a method for this.

Variance:

Variance is an important tool in the sciences, where statistical analysis of data is common. It is the square
of standard deviation of the given data-set and is also known as second central moment of a distribution. It
is usually represented by s^{2}, sigma ^{2}, Var (X) in pure Statistics.

It is calculated by mean of square minus square of mean

Var(X)= E[(X-µ)2]

Algorithm/Program:

(i) Mean:

//Use the NumPy mean() method to find the average speed:

import numpy
speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]

x = numpy.mean(speed)

print(x)

(ii) a) Median for odd numbers:

//Use the NumPy median() method to find the middle value:

import numpy

speed =

[99,86,87,88,111,86,103,87,94,78,77,85,86] x =

numpy.median(speed) print(x)

(ii) b) Median for even numbers:

//Using the NumPy module:

import numpy speed =

[99,86,87,88,86,103,87,94,78,77,85,86] x =

numpy.median(speed)

print(x)

(iii) Mode:
//Use the SciPy mode() method to find the number that appears the

most:fromscipy import stats speed =

[99,86,87,88,111,86,103,87,94,78,77,85,86] x = stats.mode(speed) print(x)

(iv) Variance: import statistics # Creating a sample

of data speed =

[99,86,87,88,111,86,103,87,94,78,77,85,86]

print("Variance of sample set is % s"

%(statistics.variance(speed)))
Roll No. Name of Date of Date of Grade Sign of Sign of
Student Performance Evaluation Student Faculty
0818IT21104 Rahul Jadhaw
8
Experiment – 2
Aim: Write a program to implement:

1. NumPy N-dimensional Array

2. Functions to Create Arrays

3. Combining Arrays Theory:

(i) NumPy N-dimensional Array:

NumPy is a Python library that can be used for scientific and numerical applications and is the tool to use
for linear algebra operations. The main data structure in NumPy is the ndarray, which is a shorthand name
for N-dimensional array. When working with NumPy, data in anndarray is simply referred to as an array.
It is a fixed-sized array in memory that contains data of the same type, such as integers or floating point
values. The data type supported by an array can be accessed via the dtype attribute on the array. The
dimensions of an array can be accessed via the shape attribute that returns a tuple describing the length of
each dimension. There are a host of other attributes. A simple way to create an array from data or simple
Python data structures like a list is to use the array() function. The example below creates a Python list of
3 Floating point values, then creates anndarray from the list and access the arrays' shape and data type.

(ii) Functions to Create Arrays

The empty() function will create a new array of the specified shape. The argument to the function is an
array or tuple that specified the length of each dimension of the array to create. The values or content of
the created array will be random and will need to be assigned before use. The example below creates an
empty 3 , 3 two-dimensional array.

The zeros() function will create a new array of the specied size with the contents filled with zero values.
The argument to the function is an array or tuple that species the length of each dimension of the array to
create. The example below creates a 3,5 zero two-dimensional array.

The ones() function will create a new array of the specified size with the contents called with one values.
The argument to the function is an array or tuple that specifies the length of each dimension of the array to
create. The example below creates a 5-element one-dimensional array.

(iii) Combining

Arrays Vertical

Stack

Given two or more existing arrays, you can stack them vertically using the vstack() function. For example,
given two one-dimensional arrays, you can create a new two-dimensional array with two rows by
vertically stacking them. This is demonstrated in the example below.

Horizontal Stack
Given two or more existing arrays, you can stack them horizontally using the hstack() function. For
example, given two one-dimensional arrays, you can create a new one-dimensional array or one row with
the columns of the first and second arrays concatenated.

Algorithm / Program:

(i)NumPy N-dimensional Array:

# create array

from numpy import array

# create array l

= [1.0, 2.0, 3.0]

a = array(l) #

display array

print(a)

# display array shape

print(a.shape)

# display array data type

print(a.dtype)

(ii)Functions to Create Arrays

a) Empyt (): # create

empty array from numpy

import empty a =

empty([3,3])

print(a)

print(a.dtype)

b) Zeros (): from

numpy import array #

create empty array from

numpy import zerosa =


zeros([3,3])

print(a)

print(a.dtype)

c) Ones(): from numpy

import array # create

empty array from numpy

import onesa =

ones([3,3])

print(a)

print(a.dtype)

(iii)Combining Arrays:

a)Vertical Stack: # create

array with vstack from

numpy import array from

numpy import vstack

# create first array a1

array([1,2,3])

print(a1)

# create second array


a2 =

array([4,5,6])

print(a2) #

vertical stack

a3 =

vstack((a1,
a2))print(a3)

print(a3.shape)

b)Horizontal Stack: #

create array with hstack

from numpy import array

from numpy import hstack

# create first array a1

array([1,2,3]) print(a1)

# create second array

a2 = array([4,5,6])

print(a2) # create

horizontal stack a3 =

hstack((a1, a2))

print(a3)

print(a3.shape)

Roll No. Name of Date Date of Grade Sign of Sign of


Student Performan Evaluation Student Faculty
ce
0818IT21104 Rahul Jadhaw
8
Experiment - 3

Aim: Write a program to implement:

1. From List to Arrays 2. Array Indexing 3. Array Slicing 4. Array Reshaping.

Theory:

1. From List to Arrays

In general, we recommend loading your data using Pandas or even NumPy functions. This
section assumes you have loaded or generated your data by other means and it is now represented
using Python lists. Let's look at converting your data in lists to NumPy arrays.

1. From 1D List to Array:

One-Dimensional List to Array

You may load your data or generate your data and have access to it as a list. You can convert a
one-dimensional list of data to an array by calling the array() NumPy function.

From 2D List to Array:

Two-Dimensional List of Lists to Array

It is more likely in machine learning that you will have two-dimensional data. That is a table of
data where each row represents a new observation and each column a new feature. Perhaps you
generated the data or loaded it using custom code and now you have a list of lists. Each list
represents a new observation. You can convert your list of lists to a NumPy array the same way
as above, by calling the array() function.

2. One-Dimensional Indexing:

Array Indexing

Once your data is represented using a NumPy array, you can access it using indexing. Let's look
at some examples of accessing data via indexing.

Generally, indexing works just like you would expect from your experience with other
programming languages, like Java, C#, and C++. For example, you can access elements using the
bracket operator [] specifying the zero-o set index for the value to retrieve.

Two-Dimensional Indexing:

Indexing two-dimensional data is similar to indexing one-dimensional data, except that a comma
is used to separate the index for each dimension.
3. Array Slicing:

Array Slicing So far, so good; creating and indexing arrays looks familiar. Now we come to array
slicing, and this is one feature that causes problems for beginners to Python and NumPy arrays.
Structures like lists and NumPy arrays can be sliced. This means that a subsequence of the
structure can be indexed and retrieved. This is most useful in machine learning when specifying
input variables and output variables, or splitting training rows from testing rows. Slicing is
specified using the colon operator : with a from and to index before and after the column
respectively. The slice extends from the from index and ends one item before the to index.

4. Array Reshaping 1D Array to 2D Array:

Reshape 1D to 2D Array It is common to need to reshape a one-dimensional array into a two-


dimensional array with one column and multiple arrays. NumPy provides the reshape() function
on the NumPy array object that can be used to reshape the data. The reshape() function takes a
single argument that specifies the new shape of the array. In the case of reshaping a one-
dimensional array into a two-dimensional array with one column, the tuple would be the shape of
the array as the rst dimension (data.shape[0]) and 1 for the second dimension.

Array Reshaping 2D Array to 3D Array

Reshape 2D to 3D Array It is common to need to reshape two-dimensional data where each row
represents a sequence into a three-dimensional array for algorithms that expect multiple samples
of one or more time steps and one or more features. A good example is the LSTM recurrent
neural network model in the Keras deep learning library. The reshape function can be used
directly, specifying the new dimensionality. This is clear with an example where each sequence
has multiple time steps with one observation (feature) at each time step. We can use the sizes in
the shape attribute on the array to specify the number of samples (rows) and columns.

Program:

1.One-Dimensional List to Array

# create one-dimensional array from

numpy import array

# list of data

data = [11, 22, 33, 44, 55]


# array of data

data =

array(data)
print(data)

print(type(data))

From 2D List to Array:

Two-Dimensional List of Lists to

Array # create two-dimensional array

from numpy import array

# list of data

data = [[11,

22], [33, 44],

[55, 66]] # array

of data data =

array(data)

print(data)

print(type(data))

2.One-Dimensional Indexing:

Array Indexing # index a one-

dimensional array from numpy

import array # define array data

= array([11, 22, 33, 44, 55])

# index data
print(data[0])

print(data[4])
# index array out of bounds

from numpy import array #

define array data = array([11,

22, 33, 44, 55]) # index data

print(data[5])

Two-Dimensional Indexing: #

index two-dimensional array

from numpy import array #

define array data = array([ [11,

22], [33, 44],

[55, 66]]) #

index data

print(data[0,0])

Two Dimensional Indexing # index

row of two-dimensional array from

numpy import array

# define array
data =

array([ [11,

22], [33, 44],

[55, 66]]) #

index data

print(data[0,])
3. Array Slicing:

# slice a one-dimensional array

from numpy import array #

define array data = array([11,

22, 33, 44, 55]) print(data[:])

4. Data Shape

# shape of one-dimensional

array from numpy import array

# define array data = array([11,

22, 33, 44, 55])

print(data.shape)

# shape of a two-dimensional array

from numpy import array

# list of data data

= [[11, 22], [33,

44],

[55, 66]] # array

of data data =

array(data)

print(data.shape)
# row and column shape of two-dimensional array

from numpy import array

# list of data data = [[11,

22],[33, 44],

[55, 66]] # array of data data =

array(data) print('Rows: %d' %

data.shape[0]) print('Cols: %d' %

data.shape[1])

Array Reshaping 1D Array to 2D

Array # reshape 1D array to 2D from

numpy import array # define array

data = array([11, 22, 33, 44, 55])

print(data.shape) # reshape

data = data.reshape((data.shape[0], 1))

print(data.shape)

Array Reshaping 2D Array to 3D Array

from numpy import array

# list of data

data = [[11,

22], [33, 44],

[55, 66]] # array of data data = array(data)

print(data.shape) # reshape data =


data.reshape((data.shape[0], data.shape[1], 1))

print(data.shape)

Roll No. Name of Date ofDate of Grade Sign of Sign of


Student Performance Evaluation Student Faculty
0818IT21104 Rahul Jadhaw
8
Experiment -4
Aim:
Write a program to implement:

1. Vector Arithmetic
2. Vector Dot Product
3. Vector-Scalar Multiplication

Theory:
Vector: -
A vector is a tuple of one or more values called scalars. Vectors are built from
components, which are ordinary numbers. You can think of a vector as a list of numbers,
and vector algebra as operations performed on the numbers in the list. Vectors are often
represented using a lowercase character such as v;

For example: v = <v1; v2; v3>

Where v1, v2, v3 are scalar values, often real values.

Vectors are also shown using a vertical representation or a column;

For example: v = <v1 v2 v3>

Defining a Vector: -
We can represent a vector in Python as a NumPy array. A NumPy array can be created from
a list of numbers. For example, a vector with the length of 4 and the integer values 1, 2, 3
and 4.
V = <1 2 3 4>

Vector Arithmetic
Two vectors of equal length can be added together to create a new third vector.
c = a + b. The new vector has the same length as the other two vectors. Each element of the
new vector is calculated as the addition of the elements of the other vectors at the same
index;For example: c = <a1 + b1; a2 + b2; a3 + b3>

Vector Subtraction
One vector can be subtracted from another vector of equal length to create a new third
vector. c = a - b.
As with addition, the new vector has the same length as the parent vectors and each element
of the new vector is calculated as the subtraction of the elements at the same indices.
c = <a1 - b1; a2 - b2; a3 - b3>
Vector Multiplication
Two vectors of equal length can be multiplied together. c = a * b. As with addition and
subtraction, this operation is performed element-wise to result in a new vector of the
same length.c = <a1* b1; a2 * b2; a3 * b3> or c = <a1b1; a2b2; a3b3>

Vector Division
Two vectors of equal length can be divided. c =a/b
As with other arithmetic operations, this operation is performed element-wise to result in a
new vector of the same length. c = <a1/b1; a2/b2; a3/b3>

Vector Dot Product


We can calculate the sum of the multiplied elements of two vectors of the same length to
give a scalar. This is called the dot product, named because of the dot operator used when
describing the operation. The dot product is the key tool for calculating vector projections,
vector decompositions, and determining orthogonality. The name dot product comes from
the symbol used to denote it.

Vector-Scalar Multiplication
A vector can be multiplied by a scalar, to scale the magnitude of the vector. To keep notation
simple, we will use lowercase s to represent the scalar value.
c = s * v or c = sv. The multiplication is performed on each element of the vector to result in
a new scaled vector of the same length. c = (s * v1; s * v2; s * v3)

Procedure:
Vector Addition: -
To add two vectors, perform element wise addition operation.
V1 = <1 4 9 5> and V2 = < 4 5 0 2>
V1 + V2 = <1+5; 4+5; 9+0; 5+2> = <6; 9; 9; 7>

Vector Subtraction: -
To subtract two vectors, perform element wise subtraction operation.
V1 = <1 4 9 5> and V2 = < 4 5 0 2>
V1 - V2 = <1-5; 4-5; 9-0; 5-2> = <-4; -1; 9; 3>

Vector Multiplication: -
To Multiply two vectors, perform element wise multiplication operation.
V1 = <1 4 9 5> and V2 = < 4 5 0 2>
V1 * V2 = <1*5; 4*5; 9*0; 5*2> = <5; 20; 0; 10>
Vector Division: -
To divide two vectors, perform element wise division operation.
V1 = <1 4 9 5> and V2 = < 1 2 3 5>
V1 / V2 = <1/1; 4/2; 9/3; 5/5> = <1; 2; 3; 1>

Vector Dot Product: -


To perform dot product between two vectors,

V1 = <1 4 9 5> and V2 = < 1 2 3 5>

V1 · V2 = 1*1 + 4*2 + 9*3 + 5*5 = 1 + 8 + 27 + 25 = 61

Vector Scalar Multiplication: -


To multiply a scalar with vector, perform element wise multiplication operation.
S = 2 and V1 = < 1 2 3 5>
S * V1 = <2*1; 2*2; 2*3; 2*5> = <2; 4; 6; 10>

Algorithm/Program:
Defining a Vector
# Import NumPy: Numerical Python
Libraryimport numpyas np

# Make a vector from


list v = np.array([1, 2, 3,
4]) print(v)

Vector Addition
# vector additionfrom
numpyimport array #
define first vector a =
array([1, 10, 4, 76, -5])
print(a)
# define second vector b
= array([4, 0, -3, 7, -5])
print(b) # add vectors c
= a + b print(c)
Vector Subtraction
# vector subtractionfrom
numpyimport array #
define first vector a =
array([1, 10, 4, 76, -5])
print(a) # define second
vector b = array([4, 0, -3,
7, -5]) print(b) # subtract
vectors c = a - b
print(c)

Vector Multiplication
# Multiplication by a scalar
import numpyas np # define
a vector v = np.array([1, 10,
4, 76, -5]) # multiply with
scalar print(2*v)

Vector Division
# vector divisionfrom
numpyimport array
# define first vector a
= array([1, 2, 3])
print(a) # define
second vector b =
array([1, 2, 3])
print(b) # divide
vectors c = a / b
print(c)

Vector Transpose
import numpyas np # Make a
random vector v =
np.random.rand(5).reshape(-1, 1) #
print vector and its shapeprint(v,
v.shape) # transpose with T
print(v.T, v.T.shape)

Vector Dot Product


# vector dot product
from numpyimport array
# define first vector s =
array([-1, 2])
print('Vector s: ', s)
# define second vector
r = array([3, 2])
print('Vector r: ', r) #
multiply vectors c =
r.dot(s) # s.dot(r)
print('Dot product: ', c)

Vector-Scalar Multiplication
# vector-scalar
multiplication from
numpyimport array # define
vector and scalar a =
array([1, 2, 3]) s = 0.5#
multiplication c = s * a
print(c)

Roll No. Name of Date of


Date of Grade Sign of Sign of
Student Performance Evaluation Student Faculty
0818IT21104 Rahul Jadhaw
8
Experiment -5
Aim: Write a program to implement:
1. Vector Norm
2. Vector L1 Norm
3. Vector L2 Norm
4. Vector Max Norm

Theory:

1. Vector Norm

Calculating the size or length of a vector is often required either directly or as part of a broader
vector or vector-matrix operation. The length of the vector is referred to as the vector norm or the
vector's magnitude. The length of a vector is a nonnegative number that describes the extent of
the vector in space, and is sometimes referred to as the vector's magnitude or the norm. The
length of the vector is always a positive number, except for a vector of all zero values. It is
calculated using some measure that summarizes the distance of the vector from the origin of the
vector space. For example, the origin of a vector space for a vector with 3 elements is (0; 0; 0).
Notations are used to represent the vector norm in broader calculations and the type of vector
norm calculation almost always has its own unique notation. We will take a look at a few
common vector norm calculations used in machine learning.

2. Vector L1 Norm

The length of a vector can be calculated using the L1 norm, where the 1 is a superscript of the L.
The notation for the L1 norm of a vector is jjvjj1, where 1 is a subscript. As such, this length is
sometimes called the taxicab norm or the Manhattan norm. L1(v) = ||v||1 The L1 norm is
calculated as the sum of the absolute vector values, where the absolute value of a scalar uses the
notation ja1j. In eect, the norm is a calculation of the Manhattan distance from the origin of the
vector space. ||v||1 = |a1| + |a2| + |a3|. In several machine learning applications, it is important to
discriminate between elements that are exactly zero and elements that are small but nonzero. In
these cases, we turn to a function that grows at the same rate in all locations, but retains
mathematical simplicity:
the L1 norm.

3. Vector L2 Norm

The length of a vector can be calculated using the L2 norm, where the 2 is a superscript of the L.
The notation for the L2 norm of a vector is jjvjj2 where 2 is a subscript. L2(v) = ||v||2 The L2
norm calculates the distance of the vector coordinate from the origin of the vector space. As such,
it is also known as the Euclidean norm as it is calculated as the Euclidean distance from the
origin. The result is a positive distance value. The L2 norm is calculated as the square root of the
sum of the squared vector values. ||v||2 =sqrt(a12+a22+a3**2) The L2 norm of a vector can be
calculated in NumPy using the norm() function with default parameters.
4. Vector Max Norm

The length of a vector can be calculated using the maximum norm, also called max norm. Max
norm of a vector is referred to as Linf where inf is a superscript and can be represented with the
infinity symbol. The notation for max norm is jjvjjinf , where inf is a subscript. Linf (v) = ||v||inf
The max norm is calculated as returning the maximum value of the vector, hence the name. ||v||
inf = max a1; a2; a3 The max norm of a vector can be calculated in NumPy using the norm()
function with the order parameter set to inf.

Program:
# vector L1 norm from numpy
import array from
numpy.linalg import norm
# define vector a =
array([1, 2, 3])
print(a) # calculate
norm l1 = norm(a, 2)
print(l1) # L1 norm

# vector max norm from math


import inf from numpy import
array from numpy.linalg
import norm
# define vector a =
array([1, 2, 3]) print(a)
# calculate norm
maxnorm = norm(a,
inf) print (maxnorm)

Roll No. Name of Date of


Date of Grade Sign ofSign of
Student Performance Evaluation Student Faculty
0818IT21104 Rahul Jadhaw
8
Experiment -6

Aim:
Write a program to implement:

1. Matrix Arithmetic
2. Matrix Scalar Multiplication
3. Matrix-Vector Multiplication
4. Matrix-Matrix Multiplication

Theory:
Matrix: -
A matrix is a rectangular arrangement of numbers into rows and columns.

An 𝑚 × 𝑛
expressedby saying that the dimensions of the matrix are 𝑚 × 𝑛.
matrix is a matrix with m rows and n columns. Sometimes this is

Matrix Arithmetic: -
Adding and subtracting matrices: You can add (or subtract) matrices by adding (or
subtracting) corresponding entries. Matrix addition is associative while subtraction isnot.

Matrix Scalar Multiplication: -


Multiplying matrices by numbers. You can multiply a matrix by a number by
multiplying each entry by the number. Python works by broadcasting this scalar tothe
shape of the matrix and then performs element wise multiplication.
Matrix Vector Multiplication –
To multiply a row vector by a column vector, the row vector must have as many columns as
the column vector has rows. To multiply a row vector by a column vector,the row vector
must have as many columns as the column vector has rows.

The multiplication between a matrix M and a vector v in which the number of


columns in M equals the number of rows in v.
So, if M is an 𝑚 ×𝑛 matrix, then the product M v is defined for 𝑛 × 1 column
vector v.If we let Mv = b, then b is an 𝑚 × 1 column vector. In other words, the number
of rows in M determines the number of rows in the product b.

Matrix Matrix Multiplication -


Matrix multiplication is a binary operation that produces a matrix from two matrices.For
matrix multiplication, the number of columns in the first matrix must be equal tothe
number of rows in the second matrix. The resulting matrix, known as the matrixproduct,
has the number of rows of the first and the number of columns of the second matrix. The
product of matrices A and B is denoted as AB.

Procedure:
Matrix Addition: -
To add two matrices, first make sure their shape matches and then perform elementwise
addition operation.

Matrix Subtraction: -
To subtract one matrix from another, first make sure their shape matches and thenperform
element wise subtraction operation.
In this case, the resultant matrix is a Diagonal Matrix and also an Identity Matrix (allIdentity
Matrices are Diagonal Matrix).

Matrix Scalar Multiplication: -


To multiply a scalar with matrix, broadcast the scalar to the shape of matrix and thenperform
element wise multiplication operation.

Matrix Vector Multiplication –


To multiply a vector v with matrix M, first make sure the number of columns of Vector
matches with number of rows of Matrix (if multiplying v x M), the resultant matrix will
always be a row vector of dimension number of columns of matrix M. Perform dot
product of vector v with columns of Matrix M and fill it in corresponding column of
theresultant vector.
Matrix Matrix Multiplication –
To compute the product 𝑨𝑩 of two matrices, take the dot products of the rows of Awith the
columns of B.

The number of columns in A should equal the number of rows of B. Thus, if A is an 𝑚


In order for the multiplication to work, the matrices must have compatible dimensions:

× 𝑛 matrix and B is an 𝑛 × 𝑝 matrix, 𝑨𝑩 will be an 𝑚 × 𝑝 matrix.

Algorithm/Program:
Defining a Matrix: -
# Import NumPy: Numerical Python
Library import numpyas np # Defining a
matrix mat = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

print("Matrix: ")
print(mat, mat.shape)

Matrix Addition: -
# Import NumPy: Numerical Python Library
import numpyas np
# Defining matrices mat1
= np.array([[1, 2, 3],
[4, 8, 0],
[3, 4, 7]])
print(mat1, mat1.shape)
mat2 = np.array([[8, 7,
6],
[5, 1, 9],
[6, 5, 2]])
print(mat2, mat2.shape) #
Addition of two matrices
print("Resultant Matrix:
")
print(mat1 + mat2)

Matrix Subtraction: -
# Import NumPy: Numerical Python Library
import numpyas np

# Defining matrices mat1


= np.array([[1, 2, 3],
[4, 8, 0],
[3, 4, 7]])
print("Matrix 1: ")
print(mat1,
mat1.shape)

mat2 = np.array([[0, 2,
3],
[4, 7, 0],
[3, 4, 6]])
print("Matrix 2: ")
print(mat2,
mat2.shape)

# Subtraction of two
matrices print("Resultant
Matrix: ") print(mat1 -
mat2)

Matrix Division: -
# Import NumPy: Numerical Python Library
import numpyas np

# Defining matrices mat1


= np.array([[2, 5, 8],
[4, 8, 6],
[9, 4, 8]])
print("Matrix 1: ")
print(mat1,
mat1.shape)

mat2 = np.array([[1, 5,
4],
[4, 2, 3],
[3, 1, 4]])
print("Matrix 2: ")
print(mat2,
mat2.shape)

# Division of two matrices


print("Resultant Matrix: ")
print(mat1 / mat2)
Matrix Scalar Multiplication: -
# Import NumPy: Numerical Python Library
import numpyas np

# Defining matrices
print("Matrix: ") mat =
np.array([[1, 2, 3],
[4, 8, 0],
[3, 4, 7]])
print(mat, mat.shape)

# Define a scalarscalar
= 2 print("Scalar: ")
print(scalar)

# Scalar Matrix
Multiplication sca_mult =
scalar * mat print("Resultant
Matrix")
print(sca_mult, sca_mult.shape)

Matrix Vector Multiplication: -


# Import NumPy: Numerical Python Library
import numpyas np

# Defining vectorvec = np.array([1,


0, 1]).reshape(1, -1) print("Vector: ")
print(vec, vec.shape)
# Defining matrix mat =
np.array([[0, 2, 3],
[4, 7, 0],
[3, 4, 6]])
print("Matrix: ")
print(mat,
mat.shape)

# Multiplying a row vector with matrix


print("Resultant Matrix: ")
print(np.matmul(vec, mat))
Matrix Matrix Multiplication: -
# Import NumPy: Numerical Python Library
import numpyas np

# Defining matrices mat1


= np.array([[1, 2, 3],
[4, 8, 0],
[3, 4, 7]])
print("Matrix 1: ")
print(mat1,
mat1.shape)

mat2 = np.array([[0, 2,
3],
[4, 7, 0],
[3, 4, 6]])
print("Matrix 2: ")
print(mat2,
mat2.shape)

# Multiplication of two
matricesmat3 = np.matmul(mat1,
mat2) print("Resultant Matrix: ")
print(mat3, mat3.shape)

Roll No. Name of Date Date of Grade Sign of Sign of


Student Performan Evaluation Student Faculty
ce
0818IT21104 Rahul Jadhaw
8

You might also like