0% found this document useful (0 votes)
14 views69 pages

Cam 6612 Projectfile

Uploaded by

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

Cam 6612 Projectfile

Uploaded by

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

CALCULUS AND MATRICES

(24APS1107)

Practical File

Bachelor of Engineering
(Electrical Engineering with Minor CSE)

SUBMITTED BY
Abhishek Babbar
2410996604

SUBMITTED TO
Ms. Manisha Devi
Assistant Professor
Jul - Dec 2024
DEPARTMENT OF ELECTRICAL ENGINEERING, CUIET-AE

CHITKARA UNIVERSITY, PUNJAB


CALCULUS AND MATRICES
(24APS1107)

INDEX
Sr. No. Title Date

1 Python Basics 28/08/24

2 Operators in Python 03/09/24

3 Conditional Statements and Loops in Python 10/09/24

4 Loops in Python 18/09/24

5 Data Structures in Python 01/10/24

6 Slicing a list 08/10/24

7 Matrices 16/10/24

8 System of linear equation 22/10/24

9 Singular Value Decomposition 05/11/24


10 3D-Matrices 09/11/24

11 Locating elements and slicing in 3D-Matrices 13/11/24

12 Partial Differentiation 19/11/24

13 Jacobian 20/11/24

14 Taylor's expansion and maxima minima 23/11/24


Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE

Date: 28/08/24

Topic: Python Basis

LaTeX

Equation of a circle with centre as origin

x2+ y2=r2

√(¿x2+1)¿

#First Program in Python


print("Welcome to Chitkara University")
Welcome to Chitkara University
print("My name is Amarjeet ")
My name is
Amarjeet
print(7) 7

print(3.14)

3.14

Type of data can be checked using type(variable_name) command

print(type(a))
print(type(b))
print(type(univ))

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
<ipython-input-5-8b5a6abd519a> in <cell line: 1>()
----> 1 print(type(a))
2 print(type(b))
3 print(type(univ))
NameError: name 'a' is not defined
Type Conversion

Question 1. Write a command to print your name.

#answer
print("My name is Amarjeet ")
univ = "Chitkara University"
print(univ)
Chitkara University
x = 5

print(x)

DATA TYPES

The following data types are defined in Python:

Integers: Whole number, say 5

Floats: Decimal Numbers, say 3.14

Strings: Text, say "Chitkara University

Booleans: True/False values (case sensitive)


x=5
y=4.567
univ="Chitkara University"
print(x)
print(y)
print(univ)

5
4.567
Chitkara University

Syntax to find type of data

type(Variable_name) To

print data

typeprint(type(Variable_nam

e))
print(type(x))
<class 'int'>
print(type(y))
print(type(univ))

<class 'float'>
<class 'str'>

print(int(y))

Data type conversion 1.


int(variable_name)

• converts the input parameter to integer type

2. float(variable_name)

• converts the input parameter to float type

3. str(variable_name)
• converts the input parameter to string type

Let us convert the integer type variable x to a float type variable X.

x= 5
print(type(x))
<class 'int'>
X=float(x)
print(x)
print(type(x))

5
<class 'int'>

Let us convert the integer type variable x to a string type variable S.


print(str(x))
5
print(str(X))
5.0
Let us convert float to inr and str
print(y)
print(type(y))
4.567
<class 'float'>

Conversion of float to int using int(variable_name)


C1 = int(y)
print(C1)
print(type(C1))

4
<class 'int'>
print(str(y))
4.567
C2 = str(y)
print(C2)
print(type(C2))
4.567
<class 'str'>

Conversion of string to int and float


print(univ)

Chitkara Universit y

print(type(univ))

<class 'str'>

C3 = int(univ)
print(C3)
print(type(C3))

----------------------------------------------------------------------
-----
ValueError Traceback (most recent call
last)
<ipython-input-23-48eba305f524> in <cell line : 1>()
----> 1 C3 = int(univ )
2 print(C3 )
3 print(ty pe(C3))

ValueError: invalid literal for int() with base 10: 'Chitkara


University'
Question 2. Check if a string can be converted to float type
C4 = float(univ)
print(C4)
print(type(C4))

----------------------------------------------------------------------
-----
ValueError Traceback (most recent call
last)
<ipython-input-24-f7e9bbc51619> in <cell line: 1>()
----> 1 C4 = float(univ)
2 print(C4)
3 print(type(C4))

ValueError: could not convert string to float: 'Chitkara University'

Question 3. Take a number as string type and check if digits can be converted to float and int
roll_no = "2410996612"
print(type(roll_no))
print(int(roll_no))
print(float(roll_no))

<class 'str'>
2410996612
2410996612.0
Question 4. Define variables a,b, c with values -5,-15.85,2000.98823 respectively.

a = -5 b = -
15.85 c =
2000.98823

Question 5. Print the values of the variables.


print(a)
print(b)
print(c)
-5
-15.85
2000.98823

Question 6. Print the data type of all variables

print(type(a))
print(type(b))
print(type(c))
<class 'int'>
<class 'float'>
<class 'float'>

Question 7. Convert the integers to float and strings, floats to integers and strings and display the
converted variable and type.

C5 = float(a)
print(C5)
print(type(C5))

C6 = str(a)
print(C6)
print(type(C6))

C7 = str(b)
print(C7)
print(type(C7))

C8 = int(b)
print(C8)
print(type(C8))

C9 = int(c)
print(C9)
print(type(C9))

C10 = str(c)
print(C10)
print(type(C10))

-5.0
<class 'float'>
-5
<class 'str'>
-15.85
<class 'str'>
-15
<class 'int'>
2000
<class 'int'>
2000.98823
<class 'str'>

Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE


Date: 3/09/24

Topic: Operations in Python

1. ARITHMETIC OPERATORS:

Addition : '+'

Subtraction : '-'

Multiplication : '*'

Division : '/'

Modulus : '%'

Exponentiation : '**'

Floor Division : '//'

Write down a program to find the values of the following and print the output.

1. 4+2
x=4+2 print(x)

1. 2+4^3
y=2+4**3 print(y)

66

1. 2+4^3-5
print(2+4**3-5)

61

1. 2^4^3
print(2**4**3)

18446744073709551616

1. COMPARISON OPERATORS:

Equal to : '=='

Not Equal to : '!='

Greater than : '>'

Less than : '<'


Greater than or equal to : '>='

Less than or equal to : '<='

Question: Define some variables a,b,c. Assign some random values integers or floats. check

1. Whether the numbers follow associative law of addition?

(a+b)+c=a+(b+c)

1. Whether the numbers follow the commutative law of multiplication?

2. Whether b+c is greater than a?


a= 2
b= 3
c= 4
print ((a+b)+c==a+(b+c))
print (a*b==b*a) print
(b+c>a)
True
True
True

1. LOGICAL OPERATORS:
• AND : 'and'

• OR : 'or'

• NOT : 'not'
T=True F=False
print(T and F)
print(T or F)
print(not T)
False
True
False

print((a+b>c) and (a==b))


print((a+b>c) or (a==b))
print((a+b>c) and (not(a==b)))

False
True
True
Output

print("Relevant text to be displayed") print("Relevant


text to be displayed",variable)
name = "Amarjeet "
age = 19
print("My name is",name)
print("My age is", age)
print("My name is", name, "and my age is", age)
My name is
Amarjeet
My age is 19
My name is Amarjeet Singhand my age
is 19
f-string

print(f"My name is {name}")


My name is
Amarjeet
print(f"My name is name")
My name is name

Input From the user variable_name = input("relevant text


to be enetered")
name=input("Enter your name")
age=input("Enter your age")
print(name,age)
Enter your
nameAmarjeet
Enter your age19
Amarjeet
Singh19
Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE

Date: 10/09/24

Topic: Conditional statements and Loops in Python

Conditional Statements-

1. if statement
2. else statement
3. elif statement Syntax for if statement if (condition):

Statement 1

Statement 2

Statement n
Syntax for elif statement elif

(condition):

some work

Syntax for else statement else:

some work

#Check if a number is even or odd.


num1 = float(input("Enter a number: ")) if
(num1 % 2) == 0: print("The number", num1,
"is divible by 2") print("The number", num1,
"is even") else: print("The number", num1,
"is odd")

Enter a number: 8
The number 8.0 is divible by 2
The number 8.0 is even

ques- Write a program to check if a number is positive, negative or zero.

num2 = float(input("Enter a number: ")) if


num2 > 0: print("The number", num2, "is
positive") elif num2 == 0: print("The
number", num2, "is zero") else:
print("The number", num2, "is negative")
Enter a number: -594.255
The number -594.255 is negative

ques- Write a program to check if the quadric equation

ax2+bx+c=0
has real and distinct roots, real and equal roots, or imaginary roots.

1. Input from the user the values of a,b and c. 2.

Save the value

b2−4ac

in d.

3. Check

d=b2−4ac
is positive, negative or zero.

a=int(input("Enter the value of a: "))


b=int(input("Enter the value of b: "))
c=int(input("Enter the value of c: "))
d=b**2-4*a*c if d>0: print("The roots
are real and distinct") print("d is
positive") elif d==0: print("The roots
are real and equal") print("d is zero")
else: print("The roots are imaginary")
print("d is negative")

Enter the value of a: 1


Enter the value of b: 4
Enter the value of c: 0
The roots are real and distinct
d is positive

question Write a program to find the greatest of three numbers entered by the user
a=int(input("Enter the value of a: "))
b=int(input("Enter the value of b: "))
c=int(input("Enter the value of c: "))
if a>b and a>c:
print("a is greater")
elif b>a and b>c:
print("b is greater")
else: print("c is
greater")
Enter the value of a: 2
Enter the value of b: 4
Enter the value of c: 3
b is greater

question: Let two forces acting on a body be 5 Newton and -5 Newton. Check if the body is in
equilibrium or not. (condition for equilibrium is sum of all the forces acting on abody is equal to zero.)

f1 = 5 f2 = -5 if f1 + f2 == 0: print("The body is in
equilibrium") else: print("The body is not in
equilibrium")

The body is in equilibrium

Nested conditional statement


ques- check the divisibility of a number by 6.

x=int(input("Enter a number: ")) if x%6==0:


print("The number is divisible by 6") else:
print("The number is not divisible by 6")
Enter a number: 20
The number is not divisible by 6
#Example of nested conditional statement
numb4= int(input("Enter a number: ")) if
numb4%2==0:

if numb4%3==0: print("The number is divisible by 6") else:


print("The number is not divisible by 3, hence not divisible by
6. ") elif (numb4%2!=0 and numb4%3==0): print("The number is not
divisible by 2, hence not divisible by 6.") else: print("The number is
not divisible by 2 and 3 , hence not divisible by 6.")
Enter a number: 6
The number is divisible by 6

#loops in python

1. for loop

2. while loop
Syntax of 'for' loop for

iiterative_variable in range ():

some work

range(start,stop,step_size)

By default: start=0. step_size=1

Iteration: Multiple repetition of same operator for different set of values.


for i in range(2,10,2):
print(i)

2
4
6
8

for i in range(1,12,2):
print(i)

1
3
5
7
9
11
ques- find the sum of first 10 natural numbers using the for loop
sum = 0 for i in range(1,11): sum=sum+i
print(sum)

55

ques- find the sum of first n natural numbers using the for loop
sum = 0
n=int(input("Enter the value of n: "))

if (n>0 and type(n)==int):


for i in range(1,n+1):
sum=sum+i print(sum)

else: print("Invalid
input")
Enter the value of n: -6
Invalid input

ques - calculate the current passing through a circuit based on user provided voltage and
resistance values. use the formula, voltage = current x resistance , i.e current =
voltage/resistance resistance should be positive and non zero
v=float(input("Enter the value of voltage (in volts): "))
r=float(input("Enter the value of resistance (in ohms): "))
if (r>0): i=v/r
print("The current is: ",i, "ampere") else :
print("Resistance should be positive and non zero")

Enter the value of voltage (in volts): 10


Enter the value of resistance (in ohms): 20
The current is: 0.5 ampere

Exercise 3. Calculate the total resistance for n resistors connected in series.

initialize the total resistance as zero. get the number of resistors as input from

the user.

check the number to be positive integer get resistance of each

resistor and keep adding to the total sum. print the final sum print

the table of n using for loop

n=int(input("Enter the number: " ))


if n>0:
for i in range(1,6):
print(n*i)
else:
print("Invalid input" )

Enter the number: 6 4


64
128
192
256
320

ques. find factorial of a number using for loop


n=int(input("Enter the value of n: "))

if (n>0 and type(n)==int):


fact=1 for i in
range(1,n+1):
fact=fact*i
print(fact) else:
print("Invalid input")
Enter the value of n: 5
120

Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE

Date: 18/09/24

Topic: Loops in Python

While loop Syntax for while loop


iterative_variable=initial value while (condition on
iterative_variable); the command to be executed
increment in iterative_variable ques- print numbers
from 1 to 5 using while loop
i = 1 while (i
< 6):
print(i)
i=i+1

1
2
3
4
5
ques- print all even numbers starting from 1 to 10
i = 0 while (i
< 11):
print(i)
i=i+2

0
2
4
6
8
10
ques- print all odd numbers starting from 1 to 10

i = 1 while (i
< 11):
print(i)
i=i+2

1
3
5
7
9
ques print numbers from 10 to 1

i = 10 while (i < 11 and


i > 0): print(i) i=i-
1

10
9
8
7
6
5
4
3
2
1

ques - print numbers 10,8,6,4,2,0


i = 10 while (i < 11 and i
> -1):
print(i)
i=i-2

10
8
6
4
2
0
ques- print the table of n using while loop

n = int(input("Enter the number: "))


i = 1 if (n>0): while (i < 11):
print(n*i)
i=i+1

Enter the number: 5


5
10
15
20
25
30
35
40
45
50

ques- find the factorial of a number n using while loop. compute the factorial only if the number is
positive integer, otherwise print it cant be computed
n = int(input("Enter the number: ")) if (n>0): i = 1
fact = 1 while (i<=n): fact = fact*i i=i+1
print(fact) else: print("The number is invalid so
cannot be computed")
Enter the number: 5
120

ques - find the factorial of a number n using while loop.


n = int(input("Enter the number: ")) if (n>0): fact
= 1 for i in range (1,n+1): fact = fact*i
print(fact) else: print("The number is invalid so
cannot be computed")
Enter the number: 5
120

Break statement: Terminated the loop prematurely.

Continue Statement: Skips the current iteration and moves to the next
#eg of break statement

for i in range (10):


if (i==5): break
print(i)

0
1
2
3
4 #eg of continue

statement

for i in range (10):


if (i==5):
continue print(i)

0
1
2
3
4
6
7
8
9

1. calculate the total resistance of n resistors connected in series.

n = int(input("Enter the number of resistors: "))


totalr = 0 if (n>0):
for i in range (1,n+1): r = float(input(f"Enter the
resistance of resistor{i}: ")) totalr = totalr + r
print("Total Resistance is" ,totalr,"ohm")
else: print("Invalid input")

Enter the number of resistors: 2


Enter the resistance of resistor1: 3.6
Enter the resistance of resistor2: 5.4
Total Resistance is 9.0 ohm

1. Calculate the gravitational force between 2 objects of masses m1 kg and m2 kg seperated by


distance of r meters.

a. get masses as input and type float

b. get the distance r and float type


c. if r is less than or equal to 0, G = 6.6x10^(-11) and apply g_force = G x m1 x m2/r^2

d. if r is greater than 0, compute g_force


m1=float(input("Enter the mass of object 1 (in kg): "))
m2=float(input("Enter the mass of object 2 (in kg): "))
r=float(input("Enter the distance between the objects (in m): "))
if (r>0): g_force=(6.67*(10**-11)*m1*m2)/r**2
print("The gravitational force between the objects is",g_force,"N")
else: print("Invalid value of r")
Enter the mass of object 1 (in kg): 25
Enter the mass of object 2 (in kg): 533.4
Enter the distance between the objects (in m): 25
The gravitational force between the objects is 1.4231112e-09 N

ques. calculate the velocity of an object under free fall from a given height usinf time increments
considering gravitational acceleration. a. initialize time to 0

b.

t=0
v=0
ts=1
g=9.8
h=float(input("Enter the height : ")) while (h>0): t=t+ts v=+g*ts
h=h-(v*t+g*t**2/2) print(f"at time{t}, velocity{v}, the object has
height {h} meters")

if h<=0: print(f"at time{t}, velocity{v}, the object has reached


ground")

Enter the height : 255.4


at time1, velocity9.8, the object has height 240.70000000000002 meters
at time2, velocity9.8, the object has height 201.5 meters at time3,
velocity9.8, the object has height 128.0 meters at time4, velocity9.8,
the object has height 10.399999999999991 meters at time5, velocity9.8,
the object has height -161.10000000000002
meters
at time5, velocity9.8, the object has reached ground
ques - calculate the final velocity of an object with initial velocity of 20m/s, subject to constant
deacceleration of 5m/s^2 over 5 seconds. check if the object has stopped. o.e if final velocity is 0

iv=20 a=-5 t=5 vf=iv+a*t if (vf>0): print(vf) else:


print("The object has stopped")

The object has stopped


Functions in python

1. build in functions- Design to perform common tasks like print, type check etc

2. user defined functionssyntax = def func_name

(parameter1,parameter2,...,parameter(n)): some work

def area_circle(): r=6 area=3.14*r**2


return area area_circle()

113.04

Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE

Date: 1/10/24

Topic: Data Structures in Python

#example of multiple output function def


multiple_operations(number1,number2): return
number1+number2,number1number2,number1*number2,number1/
number2 multiple_operations(3,4)

(7, -1, 12, 0.75)

Data Structures in Python

Data structures are organized ways to store, manage and m anipulate data in a computer so that it can
be used efficiently.

Types of data structures in Python

There are several built-in data structure in python, each serving specific purpose:

1. Lists
2. Tuples
3. Sets
4. Dictionaries
5. Strings
6. Arrays
7. Stacks and queues
8. Linked Lists
9. Trees
10. Graphs

#1. Lists
e.g first_list=[1,2,3,4]
first_list=[1,2,3,4]
print(first_list)
print(type(first_list))
[1, 2, 3, 4]
<class 'list'>

second_list=[1,"Chitkara", 3.14,first_list,True]
print(second_list) print(type(second_list))
[1, 'Chitkara', 3.14, [1, 2, 3, 4], True]
<class 'list'>
third_list=[]
print(third_list)
print(type(third_list))
[]
<class 'list'>
print(len(first_list))
print(len(second_list))
print(len(third_list))

4
5
0

Syntax for accessing elements in a list print(list_name


[index_of_element_to_be_accessed])

print(first_list[2]) print(first_list[-
2]) print(second_list[1])
print(second_list[-4])
print(second_list[1])
print(second_list[3][2])

3
3
Chitkara
Chitkara
Chitkara
3

Exercise-

1. Define the following list - test_list=[1,[4,5],[6,7,8],[10,11,[-12,-13,-14]]]

2. Determine the length of the list.


3. Write the command to access -13 from positive index.

4. Write the command to access -13 from negative index.

test_list=[1,[4,5],[6,7,8],[10,11,[-12,-13,-14]]]
print(len(test_list)) print(test_list[3][2][1])
print(test_list[3][-1][-2])

4
-13
-13

Operations on List

1. The elements of a list may be modified using the following cmd:

list_name[i]=new_value

#e.g 1 first_list[3]=40 print(first_list)

[1, 2, 3, 40]

1. Some new elements may be added to the list using the cmd:

name_of_list.append(element_to_be_added)
#e.g 2
first_list.append(5)
print(first_list)

first_list.append(30)
print(first_list)
[1, 2, 3, 40, 5, 5]
[1, 2, 3, 40, 5, 5, 30]

1. An element may be inserted into the list by using the cmd:

name_of_list.insert(index_where_insertion_is_to_be_made,element_to_be_inserted)
#e.g 3
print(first_list)
first_list.insert(2,20)
print(first_list) first_list.insert(-
2,60) print(first_list)
[1, 2, 3, 40, 5, 5, 30]
[1, 2, 20, 3, 40, 5, 5, 30]
[1, 2, 20, 3, 40, 5, 60, 5, 30]
1. An element may be removed from the list by using the cmd:

name_of_list.remove(element_to_be_removed)

print(first_list)
first_list.remove(5)
print(first_list)
[1, 2, 20, 3, 40, 5, 60, 5, 30]
[1, 2, 20, 3, 40, 60, 5, 30]
five_list=[1,2,2,3,2,5,4,3,2]
print(five_list)
[1, 2, 2, 3, 2, 5, 4, 3, 2]
five_list.remove(2)
print(five_list)

while 2 in five_list:
five_list.remove(2)
print(five_list) [1,
3, 5, 4, 3]

exercise 1. Can you count and list out distinct elements in the list?
six_list=[1,2,2,3,2,5,4,3,2]
print(six_list)
print(len(six_list))

distinct_elements_in_six_list=[] for i in
range(len(six_list)): if six_list[i] not in
distinct_elements_in_six_list:
distinct_elements_in_six_list.append(six_list[i])
print(distinct_elements_in_six_list)

[1, 2, 2, 3, 2, 5, 4, 3, 2]
9
[1, 2, 3, 5, 4]

exercise 2. Can you count the number of times an elements is present in six_list
print(six_list.count(2))
print(six_list.count(3))

4
2
Slicing a list
Slicing in a list refers to the process of extracting a subset of elements from a list by specifying a range of
indices.

The basic syntax for slicing a list is:- new_list=original_list [start_index:stop_index:step]


1. start_index: index of the starting location (included)
2. stop_index: index of the terminal location (excluded)
3. step: next jump to index (optional)
print(five_list) print(len(five_list))

five_list_a=five_list[0:4] print(five_list_a)

[1, 2, 2, 3, 2, 5, 4, 3, 2]
9
[1, 2, 2, 3]
five_list_b=five_list[2:7:1] print(five_list_b)
[2, 3, 2, 5, 4]
five_list_c=five_list[1:9:2] print(five_list_c)
[2, 3, 5, 3]
five_list_d=five_list[2:len(five_list):3] print(five_list_d)
[2, 5, 2]
print(five_list) five_list_e=five_list[2:]
print(five_list_e)
[1, 2, 2, 3, 2, 5, 4, 3, 2]
[2, 3, 2, 5, 4, 3, 2]
five_list_f=five_list[:6] print(five_list_f)
[1, 2, 2, 3, 2, 5]
five_list_f=five_list[:] print(five_list_f)
[1, 2, 2, 3, 2, 5, 4, 3, 2]
print(five_list) print(len(five_list))
[1, 2, 2, 3, 2, 5, 4, 3, 2]

[2, 5, 4, 3]

five_list_a=five_list[-5:-1] print(five_list_a)

five_list_b=five_list[-7:-2] print(five_list_b)
[2, 3, 2, 5, 4]
five_list_b=five_list[-7:] print(five_list_b)
[2, 3, 2, 5, 4, 3, 2]
print(five_list[::-1]) #reversing
[2, 3, 4, 5, 2, 3, 2, 2, 1]
list_11=[1,2,4,"name",3.14,"class"] for
i in list_11: print(i)

1
2 4 name
3.14 class

for i in range(len(list_11)):
print(i) print(list_11[i])

0
1
1
2
2
4 3
name
4
3.14
5 class

TUPLES A tuple is an ordered, immutable collection of elements. Once created, the elements of a tuple
cannot be changed.
tuple_one=(2, -7, 0, "class", "chitkara university", -8, -12.35)
print(tuple_one) print(len(tuple_one)) print(tuple_one[3])
print(type(tuple_one))
(2, -7, 0, 'class', 'chitkara university', -8, -12.35)

class 7
class 'tuple'>
<

NOTE: All the slicing operations as studied for list environment are applicable to the tuples as well.

Exercise :

1. Create new tuples out of tuple_one specifying only the start position.
2. Create new tuples out of tuple_one specifying only the terminal position.
3. Create new tuples out of tuple_one specifying the start and terminal positions.
4. Create new tuples out of tuple_one specifying the start and terminal positions and steps.
5. Create new tuples out of tuple_one using negative indices.

#1
touple2=tuple_one[0:]
print(touple2)
(2, -7, 0, 'class', 'chitkara university', -8, -12.35)
#2
touple3=tuple_one[:8]
print(touple3)
(2, -7, 0, 'class', 'chitkara university', -8, -12.35)
#3
touple4=tuple_one[0:8]
print(touple4)
(2, -7, 0, 'class', 'chitkara university', -8, -12.35)
#4
touple5=tuple_one[0:8:3]
print(touple5)
(2, 'class', -12.35)
#5
touple6=tuple_one[-8:]
print(touple6)
find the values of voltages corresponding tocurent = [10,20,5,9]
resistance= [2.5,4,0.9,3] using formula v=i*r

current=[10,20,5,9]
resistance=[2.5,4,0.9,3]
voltage=[current[0]*resistance[0],current[1]*resistance[1],current[2]*
resistance[2],current[3]*resistance[3]] print(voltage)
[25.0, 80, 4.5, 27]
voltage=[] for i in range(4):
voltage.append(current[i]*resistance[i])
print(voltage)
[25.0, 80, 4.5, 27]
def calc_voltage(current,resistance):
voltage=[current*resistance for current,resistance in
zip(current,resistance)]
return voltage current =
[10,20,5,9] resistance =
[2.5,4,0.9,3]
voltage=calc_voltage(current,resistance)
print(voltage)

[25.0, 80, 4.5, 27]


set_one={'a','b','c','d','b','e','f','b'}
print(set_one) print(type(set_one))
print(len(set_one))
'd', 'e', 'f', 'b', 'c', 'a'} {
class 'set'>

<
6

set_two={9, 11, 12, 13, -1, 4, 11, 3, 9}


print(set_two) print(type(set_two))
print(len(set_two))
{3, 4, 9, 11, 12, 13, -1}
class 'set'> <
7
Name- Amarjeet

Roll no - 2410996612

Branch - Be - ee - minor cse

Date- 16/10/24

NumPy: NumPy is a python library (Numerical python). NumPy is the fundamental package for scientific
computing in python. It is python library that provides a multidemensional array such as matrices and as
assortment of routines for fast operaions on arrays.

We will learn to enter elements of a matrix and perforn some basic operations on a matrix.
import numpy as np
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)

[[1 2 3]
[4 5 6]
[7 8 9]]
exercise: Enter a row matrix and a column matrix.
import numpy as np
b=np.array([[1,2,3]])
print(b)
c=np.array([[1],[2],[3]])
print(c)

[[1 2 3]]
[[1]
[2]
[3]]
Operations on a matrix:

1. Addition of two matrices

d=np.array([[5,10,15],[6,12,18],[7,14,21]])
print("a=",a) print("d=",d)
e=np.add(a,d) #Addition of two matrices
print("SUm of e and a is=\n", e)

a= [[1 2 3]
[4 5 6]
[7 8 9]] d=
[[ 5 10 15]
[ 6 12 18]
[ 7 14 21]]
SUm of e and a is =
[[ 6 12 18]
[10 17 24]
[14 22 30]]

f=np.subtract(a,d) #Subtraction of two matrices


print("Difference of e and a is= \n", f)
g=np.subtract(d,a) #Subtraction of two matrices
print("Difference of a and e is= \n", g)

Difference of e and a is=


[[ -4 -8 -12]
[ -2 -7 -12]
[ 0 -6 -12]]
Difference of a and e is=
[[ 4 8 12]
[ 2 7 12]
[ 0 6 12]]

1. Order of a matrix

2. Accessing an element of a matrix


print(np.shape(a)) #order of a matrix
print(a.shape) #order of a matrix
print(a.size) #size of a matrix

(3, 3)
(3, 3)
9
print(a[0,0])
print(a[0,1])
print(a[0,2])
print(a[1,0])

1
2
3
4
exercise- Access all diagonal elements of matric a and non-diagonal elements of matrix d

print(a[0,0])
print(a[1,1])
print(a[2,2])
print(d[0,1])
print(d[0,2])
print(d[1,0])
print(d[1,2])
print(d[2,0])
print(d[2,1])

1
5
9
10
15
6
18
7
14

1. Division of corresponding elements of two matrices

2. Multiplication of corresponding elements of two matrices


print("a = ",a)
print("d = ",d)
h=np.divide(a,d) #Element wise division
print("Division of a and d is= \n", h)
i=np.multiply(a,d) #Element wise multiplication
print("Multiplication of a and d is= \n", i)

a = [[1 2 3]
[4 5 6]
[7 8 9]]
d = [[ 5 10 15]
[ 6 12 18]
[ 7 14 21]]
Division of a and d is=
[[0.2 0.2 0.2 ]
[0.66666667 0.41666667 0.33333333 ]
[1. 0.57142857 0.42857143 ]]
Multiplication of a and d is=
[[ 5 20 45]
[ 24 60 108]
[ 49 112 189]]

7, Product of two matrices

m=np.array([[2,3],[5,6],[8,9]])
print(m) print(m.shape)
print(np.dot(a,m)) #product of two matrices
[[2 3]
[5 6]
[8 9]]
(3, 2)
[[ 36 42]
[ 81 96]
[126 150]]

print("A= ", a)
print(np.transpose(a)) #Transpose of a matrix
print(a.T)

A= [[1 2 3]
[4 5 6]
[7 8 9]]
[[1 4 7]
[2 5 8]
[3 6 9]]
[[1 4 7]
[2 5 8]
[3 6 9]]

# sum of a+d = e
print("Sum of a and d = \n", e)
y = e.T
print("Transpose of (a+d) = \n", y)
z=np.add(a.T,d.T)
print("Sum of a transpose and d transpose \n", z)
print(y==z)

Sum of a and d =
[[ 6 12 18]
[10 17 24]
[14 22 30]]
Transpose of (a+d) =
[[ 6 10 14]
[12 17 22]
[18 24 30]]
Sum of a transpose and d transpose
[[ 6 10 14]
[12 17 22]
[18 24 30]]
[[ True True True]
[ True True True ]
[ True True True ]]
1. trace of a matrix
print(a)
print(np.trace(a)) #trace of a
print(sum(a.diagonal()))

[[1 2 3]
[4 5 6]
[7 8 9]]
15
15
Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE

Date: 22/10/24

Topic: Data Structures in Python

1. square root of elements of matrices


import numpy as np
a=np.array([[3,6,12],[2,8,5],[7,14,21]])

print(a)
print(np.sqrt(a))

[[ 3 6 12]
[ 2 8 5]
[ 7 14 21]]
[[1.73205081 2.44948974 3.46410162 ]
[1.41421356 2.82842712 2.23606798 ]
[2.64575131 3.74165739 4.58257569] ]

1. Sum of all elements of a matrix

print(np.sum(a))
78
#column wise sum of elements of a matric a
print(np.sum(a,axis=0)) #axis = 0 = column wise sum
print(np.sum(a,axis=1)) #axis = 1 = row wise sum
[12 28 38]
[21 15 42]
<class 'numpy.ndarray'>
#number of rows of a matrix
print(len(a)) #number of
columns print(len(a[0]))
#using shape print(a.shape)
print(a.shape[0])
print(a.shape[1])

3
3
(3, 3)
3
3

k = np.concatenate((a,b),axis=0) This is
to concatenate row wise k =
np.concatenate((a,b),axis=1) This is to
concatenate column wise
b=np.array([[1],[4],[7]])
k=np.concatenate((a,b),axis=1)
print(k)

[[ 3 6 12 1]
[ 2 8 5 4]
[ 7 14 21 7]]
q. check whether the following system of linear equations is consistent or not.

A=np.array([[2,3,5],[1,2,7],[4,11,3]])
B=np.array([[9],[13],[-1]])
k=np.concatenate((A,B),axis=1) print(f"The
coffecient matrix is a: {A} ") print(f"The
RHS constant matrix is b: {B} ") print(f"The
augmented matrix is k: {k} ")

The coffecient matrix is a: [[ 2 3 5]


[ 1 2 7]
[ 4 11 3]]
The RHS constant matrix is b: [[ 9]
[13]
[-1]]
The augmented matrix is k: [[ 2 3 5 9]
[ 1 2 7 13]
[ 4 11 3 -1]]

To determine rank of a matrix, we will use a package linalg (linear algebra) and the code is
np.linalg.matrix_rank(a)

x=np.linalg.matrix_rank(A)
y=np.linalg.matrix_rank(k)
print(f"The rank of the matrix is: {np.linalg.matrix_rank(A)}")
print(f"The rank of the augmented matrix is:
{np.linalg.matrix_rank(k)}") if x==y==A.shape[1]:
print("The system is consistent and has unique solution")
solution=np.linalg.solve(A,B)

print(f"The solution is: {solution}") elif


(x==y<A.shape[1]): print("the sum is consistent and has
infinite solutions") else: print("The system is
inconsistent")
The rank of the matrix is: 3
The rank of the augmented matrix is: 3
The system is consistent and has unique solution
The solution is: [[ 1.]
[-1.]
[ 2.]]

m=np.array([[1,3,2],[4,4,-3],[5,1,2]])
n=np.array([[13],[3],[13]])
k=np.concatenate((m,n),axis=1)
print(k)
print(f"The rank of the matrix is: {np.linalg.matrix_rank(m)}")
print(f"The rank of the augmented matrix is:
{np.linalg.matrix_rank(k)}") x=np.linalg.matrix_rank(m)
y=np.linalg.matrix_rank(k) if x==y==m.shape[1]:
print("The system is consistent and has unique solution")
solution=np.linalg.solve(m,n) print(f"The solution is:
{solution}") elif (x==y<m.shape[1]): print("the sum is
consistent and has infinite solutions") else: print("The
system is inconsistent")

[[ 1 3 2 13]
[ 4 4 -3 3]
[ 5 1 2 13]]
The rank of the matrix is: 3
The rank of the augmented matrix is: 3
The system is consistent and has unique solution
The solution is: [[1.]
[2.]
[3.]]

c=np.array([[2,0,-1],[5,1,0],[0,1,3]])
print(c)
eval,evec=np.linalg.eig(c)
print(eval)
print("x",evec)

[[ 2 0 -1]
[ 5 1 0]
[ 0 1 3]]
[0.09583914+0.j 2.95208043+1.31124804j 2.95208043-1.31124804j]
x [[-0.16853414+0.j -0.29083488-0.19535909j -
0.29083488+0.19535909j]
[ 0.931992 +0.j -0.74493569+0.j -0.74493569-0.j

[-0.32091611+0.j 0.02073396+0.56735423j 0.02073396-


0.56735423j]]

a=np.array([[-15,5],[10,-10]])
eval,evec=np.linalg.eig(a)
print(eval) print(evec)
t=(2*3.14)/(-eval**1/2)
print(t)
[-20. -5.]
[[-0.70710678 -0.4472136 ]
[ 0.70710678 -0.89442719]]
[0.628 2.512]

deta=np.linalg.det(a)
print(deta)

100.00000000000004
to make random matrix a=np.random.randint(min_val,max_val,(order))

import numpy as np
a=np.random.randint(0,10,(3,4))
print(a)

[[5 0 3 5]
[9 5 2 4]
[5 0 2 9]]

a=np.random.randint(0,2,(10,20))
print(a)

[[0 1 0 0 0 1 0 0 0 1 0 1 0 1 1 1 0 1 0 0]
[1 0 0 1 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0 0]
[1 0 0 1 0 0 0 1 1 1 1 1 1 1 0 0 0 0 1 0]
[0 0 0 0 1 1 0 0 1 1 0 0 1 0 1 1 0 0 0 0]
[0 1 0 1 1 0 0 0 1 0 1 0 1 1 0 1 0 1 1 0]
[0 1 1 0 1 1 0 0 1 0 1 0 0 1 1 0 0 0 0 0]
[0 1 0 0 1 0 1 1 0 0 1 1 0 1 1 0 1 0 1 0]
[0 1 1 1 0 1 0 0 0 0 1 0 1 1 0 1 1 1 0 1]
[1 1 0 0 0 0 1 1 0 1 0 0 1 0 0 1 1 1 1 1]
[0 0 0 1 1 1 0 0 1 1 0 0 0 1 0 0 1 0 1 1]] Record attendece of 10 students for 20
days. Mark 0 if absent and 1 if present. Write the corresponding matrix. Print a message if the attendece
is less than 70% or more than 70%.

import numpy as np
a=np.random.randint(0,2,(10,20))
print(a)
attendance_percentage = (a.sum(axis=1)/20)*100
print(f"attendance:{(a.sum(axis=1)/20)}") for i in
range(0,10): if attendance_percentage[i] >=70:
print(f"Student {i + 1}: Attendance is above 70%")
else: print(f"Student {i + 1}: Attendance is below
70%")

[[0 0 0 0 0 1 0 1 1 1 0 0 1 0 1 0 1 1 1 1]
[0 1 0 1 0 1 0 1 0 0 0 1 0 1 1 1 0 0 0 0]
[0 0 1 0 1 0 0 0 0 1 0 1 1 0 0 0 0 0 1 0]
[1 0 1 1 0 1 0 0 1 1 1 1 1 0 1 0 0 0 1 0]
[0 0 1 0 1 0 1 0 1 0 0 1 1 1 0 1 0 0 1 0]
[0 0 1 1 1 1 0 1 0 0 1 1 0 0 1 1 1 0 1 1]
[0 1 0 0 1 0 0 1 0 0 1 0 1 0 0 0 0 0 0 0]
[1 0 0 1 1 0 0 1 0 1 0 0 1 0 1 0 1 1 0 0]
[1 0 0 0 0 1 1 1 1 0 1 0 1 1 1 1 1 0 1 0]
[0 1 0 1 0 0 1 0 0 0 0 1 1 0 0 1 1 1 0 1]]
attendance:[0.5 0.4 0.3 0.55 0.45 0.6 0.25 0.45 0.6 0.45]
Student 1: Attendance is below 70%
Student 2: Attendance is below 70%
Student 3: Attendance is below 70%
Student 4: Attendance is below 70%
Student 5: Attendance is below 70%
Student 6: Attendance is below 70%
Student 7: Attendance is below 70%
Student 8: Attendance is below 70%
Student 9: Attendance is below 70%
Student 10: Attendance is below 70%

a=np.random.randint(0,2,(10,20))
attendance_percentage = (a.sum(axis=1)/20)*100
print(f"Attendance:{a}") for i in range(10):
print(f"Student {i + 1}: Attendance Percentage =
{attendance_percentage[i]}%")
if attendance_percentage[i]>70:
print(f"Student {i + 1}: Attendance is above 70%")
elif attendance_percentage[i]==70: print(f"Student {i
+ 1}: Attendance is equal to 70%") else:
print(f"Student {i + 1}: Attendance is below 70%")
Attendance:[[0 1 0 1 0 1 1 1 1 0 0 0 1 0 1 0 1 1 1 1]
[1 1 0 0 1 1 0 1 1 0 1 1 1 1 1 0 1 1 0 1]
[0 1 0 1 0 0 0 0 1 0 0 0 1 0 1 0 0 1 1 1]
[1 0 1 0 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 0]
[1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 0 0 1 1 0]
[1 0 0 1 0 0 0 0 1 1 0 1 1 0 1 0 0 0 0 0]
[0 0 0 1 0 1 0 1 0 1 0 1 1 0 0 0 0 0 0 1]
[1 0 1 1 0 1 1 1 0 0 1 1 0 1 0 1 0 0 1 1]
[1 0 0 0 0 0 1 0 1 0 0 1 0 0 1 1 1 1 0 0]
[0 1 1 0 1 1 1 1 0 1 1 0 0 0 0 0 0 0 1 0]]
Student 1: Attendance Percentage = 60.0%
Student 1: Attendance is below 70%
Student 2: Attendance Percentage = 70.0%
Student 2: Attendance is equal to 70%
Student 3: Attendance Percentage = 40.0%
Student 3: Attendance is below 70%
Student 4: Attendance Percentage = 55.00000000000001%
Student 4: Attendance is below 70%
Student 5: Attendance Percentage = 50.0%
Student 5: Attendance is below 70%
Student 6: Attendance Percentage = 35.0%
Student 6: Attendance is below 70%
Student 7: Attendance Percentage = 35.0%
Student 7: Attendance is below 70%
Student 8: Attendance Percentage = 60.0%
Student 8: Attendance is below 70%
Student 9: Attendance Percentage = 40.0%
Student 9: Attendance is below 70%
Student 10: Attendance Percentage = 45.0%
Student 10: Attendance is below 70%
Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE

Date: 5/11/24

Topic: Singular value decomposition

Amxn=USV T (svd)

mxm, mxn, nxn


• U is a mxm matrix where columns are the unit eigen vectors of A AT.
• V is a nxn matrix where columns are the unit eigen vectors of AT A.
• S is a mxn matrix which has singular values on the main diagonal. Singular

values are the eigen values of ( AT A )1/2 . A^TA ---> λ1,λ2,......,λn.


Singular values ---> .
import numpy as np
a= np.array([[3,2,2],[2,3,-2]])
at=np.transpose(a) print("A is:
",a) print("A^T is: ",at)
b=a@at #dot product
print("AxA^T is: ",b)
ev1,ew1=np.linalg.eig(b)
print("The eigen values of AA^T is: ",ev1)
print("The eigen vectors of AA^T is: ",ew1)
u=ew1
print("U is: ",u)
b2=at@a
print("A^TA is: ",b2)
ev2,ew2=np.linalg.eig(b2)
print("The eigen values of A^TA is: ",ev2)
print("The eigen vectors of A^TA is: ",ew2)
v=ew2
print("V is: ",v)
s=np.array([[5,0,0],[0,3,0]])
print("S is: ",s)
vt=np.transpose(v)
print("USV^T is: ",u@s@vt)
A is: [[ 3 2 2]
[ 2 3 -2]]

A^T is: [[ 3 2]
[ 2 3]
[ 2 -2]]
AxA^T is: [[17 8]
[ 8 17]]
The eigen values of AA^T is: [25. 9.]
The eigen vectors of AA^T is: [[ 0.70710678 -0.70710678]
[ 0.70710678 0.70710678]]
U is: [[ 0.70710678 -0.70710678]
[ 0.70710678 0.70710678]]
A^TA is: [[13 12 2]
[12 13 -2]
[ 2 -2 8]]
The eigen values of A^TA is: [2.5000000e+01 5.0324328e-15
9.0000000e+00]
The eigen vectors of A^TA is: [[-7.07106781e-01 -6.66666667e-01
2.35702260e-01]
[-7.07106781e-01 6.66666667e-01 -2.35702260e-01]
[-4.55680392e-17 3.33333333e-01 9.42809042e-01]]
V is: [[-7.07106781e-01 -6.66666667e-01 2.35702260e-01]
[-7.07106781e-01 6.66666667e-01 -2.35702260e-01]
[-4.55680392e-17 3.33333333e-01 9.42809042e-01]]
S is: [[5 0 0]
[0 3 0]]
USV^T is: [[-1.08578644 -3.91421356 -0.70710678]
[-3.91421356 -1.08578644 0.70710678]]

u,s,v=np.linalg.svd(a)
print("U is: ",u)
print("S is: ",s)
print("V is: ",v)

U is: [[-0.70710678 -0.70710678]


[-0.70710678 0.70710678]]
S is: [5. 3.]
V is: [[-7.07106781e-01 -7.07106781e-01 -6.47932334e-17]
[-2.35702260e-01 2.35702260e-01 -9.42809042e-01]
[-6.66666667e-01 6.66666667e-01 3.33333333e-01]]

Pseudo Inverse (PI)


Inverse ->

AB=I=BA

A A−1=I=A−1A
Pseudo Inverse ->

Amxn Atnxm ≠ I mxm

Atmxn Anxm = I mxm

B=(U SV T )T=(V T)T ST U T=V ST U T

Pseudo inverse = V S1UT

V=np.array([[7.07106781e-01,2.35702260e-01,6.66666667e-01],
[7.07106781e-01,-2.35702260e-01,-6.66666667e-01],[-4.55680392e-
17,9.42809042e-01,-3.33333333e-01]])
U=np.array([[0.70710678,0.70710678],[0.70710678,-0.70710678]])
S=np.array([[5,0,0],[0,3,0]])
VT=V.T print("U=", U)
print("S=", S) print("V=", V)
print("V^T=", VT)
print("U*S*V^T=", U@S@VT)

U= [[ 0.70710678 0.70710678]
[ 0.70710678 -0.70710678]]
S= [[5 0 0]
[0 3 0]]
V= [[ 7.07106781e-01 2.35702260e-01 6.66666667e-01]
[ 7.07106781e-01 -2.35702260e-01 -6.66666667e-01]
[-4.55680392e-17 9.42809042e-01 -3.33333333e-01]]
V^T= [[ 7.07106781e-01 7.07106781e-01 -4.55680392e-17]
[ 2.35702260e-01 -2.35702260e-01 9.42809042e-01]
[ 6.66666667e-01 -6.66666667e-01 -3.33333333e-01]]
U*S*V^T= [[ 2.99999999 2. 2. ]
[ 2. 2.99999999 -2. ]]

s1=np.array([[1/5,0],[0,1/3],[0,0]])
pi=V@[email protected]
print("Pseudo Inverse=", pi)
print(pi@a) print(a@pi)

Pseudo Inverse= [[ 0.15555556 0.04444444]


[ 0.04444444 0.15555556]
[ 0.22222222 -0.22222222]]
[[ 0.55555555 0.44444444 0.22222222]
[ 0.44444444 0.55555555 -0.22222222]
[ 0.22222222 -0.22222222 0.88888889]]
[[ 9.99999998e-01 -2.35702180e-10]
[-2.35702124e-10 9.99999998e-01]]

c=np.array([[-4,-7],[1,4]])
print(c)

import sympy as sp
cp=sp.Matrix(c).charpoly()
print(cp)
print(cp.as_expr())

[[-4 -7]
[ 1 4]]
PurePoly(lambda**2 - 9, lambda, domain='ZZ' )
lambda**2 - 9
Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE

Date: 9/11/24

Topic: Matrices in 3D

#3D-Matrices
3D-Matrices are nothing but stacks of multiple 2D-matrices of same order.

import numpy as np
a=np.array([[1,2,3,4],[5,6,7,8]])
print("Matrix A is: ",a)
print(a.shape)
b=np.array([[9,10,11,12],[13,14,15,16]])
print("Matrix B is: ",b) print(b.shape)
c=np.array([[17,18,19,20],[21,22,23,24]])
print("Matrix C is: ",c) print(c.shape)

Matrix A is: [[1 2 3 4]


[5 6 7 8]]
(2, 4)
Matrix B is: [[ 9 10 11 12]
[13 14 15 16]]
(2, 4)
Matrix C is: [[17 18 19 20]
[21 22 23 24]]
(2, 4)
d=np.array([[[1,2,3,4],[5,6,7,8]],[[9,10,11,12],[13,14,15,16]],
[[17,18,19,20],[21,22,23,24]]])
print("Matrix D is: ",d)
print(d.shape)
Matrix D is: [[[ 1 2 3 4]
[ 5 6 7 8]]
[[ 9 10 11 12]
[13 14 15 16]]

[[17 18 19 20]
[21 22 23 24]]]
(3, 2, 4)
e=np.stack((a,b,c),axis=0)
print("Matrix E is: ",e)
Matrix H is: [[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]

#Transpose of 3D-Matrix

matrix.transpose(d,r,c) where

d is the desired depth r is the desired

number of rows c is the desired

number of columns
[[ 2 10 18]
[ 6 14 22]]

[[ 3 11 19]
[ 7 15 23]]

[[ 4 12 20]
[ 8 16 24]]]
Order of at2 = (4, 2, 3)
At3 = [[[ 1 2 3 4 ]
[ 9 10 11 12]
[17 18 19 20]]

[[ 5 6 7 8]
[13 14 15 16]
[21 22 23 24]] ]
Order of at3 = (2, 3, 4)
At4 = [[[ 1 5 ]
[ 9 13]
[17 21]]

[[ 2 6]
[10 14]
[18 22]]

[[ 3 7]
[11 15]
[19 23]]

[[ 4 8]
[12 16]
[20 24]]]
Order of at4 = (4, 3, 2)
At5 = [[[ 1 9 17 ]
[ 2 10 18]
[ 3 11 19]
[ 4 12 20]]

[[ 5 13 21]
[ 6 14 22]
[ 7 15 23]
[ 8 16 24]]]
Order of at5 = (2, 4, 3)

ELEMENT-WISE ADDITION
A constant number may be added to all the elements of a 3D-Matrix using the command

Matrix+constant
i=e+10
print("Matrix after adding 10 to each element of E is I:","\n", i)
Matrix after adding 10 to each element of E is I:
[[[11 12 13 14]
[15 16 17 18]]
[[19 20 21 22]
[23 24 25 26]]
[[27 28 29 30]
[31 32 33 34]]]

MATRIX-WISE MULTIPLICATION
A constant number may be multiplied to all the elements of a 3D-Matrix using the command
Matrix*constant
j=e*2
print("Matrix after multiplying 2 to each element of E is I:","\n", j)
Matrix after multiplying 2 to each element of E is I:
[[[ 2 4 6 8]
[10 12 14 16]]
[[18 20 22 24]
[26 28 30 32]]
[[34 36 38 40]
[42 44 46 48]]]

ACCESSING A SINGLE ELEMENTS


Any element of a 3D-Matrix may be accessed using the command

Matrix[i,j,k]
print("E = ",e)
E = [[[ 1 2 3 4]
[ 5 6 7 8]]
[[ 9 10 11 12]
[13 14 15 16]]

[[17 18 19 20]
[21 22 23 24]]]
print(e[1,0,1])
10
Exercise - Access elements 3,5,12,15,24,22 and 19

print(e[0,0,2])
print(e[0,1,0])
print(e[1,0,3])
print(e[1,1,2])
print(e[2,1,3])
print(e[2,1,1])
print(e[2,0,2])

3
5
12
15
24
22
19

print("G = ",g)
G = [[[ 1 9 17]
[ 2 10 18]
[ 3 11 19]
[ 4 12 20]]
[[ 5 13 21]
[ 6 14 22]
[ 7 15 23]
[ 8 16 24]]]
print(g[0,2,0])
print(g[1,0,0])
print(g[0,3,1])
print(g[1,2,1])
print(g[1,3,2])
print(g[1,1,2])
print(g[0,2,2])

3
5
12
15
24

22
19
Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE

Date: 13/11/24

Topic: Matrices in 3D

LOCATING AN ELEMENT IN 3D-MATRIX


An element may be located in a 3d-matrix by using the command
location=numpy.where(Matrix==element)

import numpy as np
a=np.array([[1,2,3,4],[5,6,7,8]])
print("Matrix A is: ",a)
print(a.shape)
b=np.array([[9,10,11,12],[13,14,15,16]])
print("Matrix B is: ",b) print(b.shape)
c=np.array([[17,18,19,20],[21,22,23,24]])
print("Matrix C is: ",c) print(c.shape)

Matrix A is: [[1 2 3 4]


[5 6 7 8]]
(2, 4)
Matrix B is: [[ 9 10 11 12]
[13 14 15 16]]
(2, 4)
Matrix C is: [[17 18 19 20]
[21 22 23 24]]
(2, 4)
d=np.array([a,b,c])
print("Matrix D is: ",d)
print(d.shape)
Matrix D is: [[[ 1 2 3 4]
[ 5 6 7 8]]
[[ 9 10 11 12]
[13 14 15 16]]

[[17 18 19 20]
[21 22 23 24]]]
(3, 2, 4)
location=np.where(d==3)
print(location)
location=np.where(d==6)
print(location)
location=np.where(d==7)
print(location)
location=np.where(d==23)
print(location)
location=np.where(d==17)
print(location)
location=np.where(d==15)
print(location)
(array([0]), array([0]), array([2]))
(array([0]), array([1]), array([1]))
(array([0]), array([1]), array([2]))
(array([2]), array([1]), array([2]))
(array([2]), array([0]), array([0]))
(array([1]), array([1]), array([2]))

Slicing of a 3D matrix
matrix[start_index:stop_index:step_size,start_index:stop_index:step_size,start_index:stop_inde
x:step_size]

Starting index is included,stopping index is excluded.

d1 = d[:,1,:]
print("\nMatrix d1 is:\n", d1)
print("\nshape of d1:", d1.shape)

d2 = d[1,1,:]
print("\nMatrix d2 is:\n", d2)
print("\nshape of d2:", d2.shape)

d3 = d[2,0,2]
print("\nMatrix d3 is:\n", d3)
print("\nshape of d3:", d3.shape)

d4 = d[0:1,0,1:2] print("\nMatrix d4
is:\n", d4) print("\nshape of d4:",
d4.shape)

Matrix d1 is:
[[ 5 6 7 8]
[13 14 15 16]
[21 22 23 24]]

shape of d1: (3, 4)

Matrix d2 is:
[13 14 15 16]

shape of d2: (4,)

Matrix d3 is:
19

shape of d3: ()

Matrix d4 is:
[[2]]

shape of d4: (1, 1 )

g=np.stack((a,b,c),axis =1)
print("Matrix G is: " ,g)
print(g.shape)

Matrix G is: [[[ 1 2 3 4]


[ 9 10 11 12]
[17 18 19 20] ]

[[ 5 6 7 8]
[13 14 15 16]
[21 22 23 24]]]
(2, 3, 4)

Slice 3d matrix g to get matrices -

1. [[9,11] [13,15]]

2. [[1,2,3,4] [5,6,7,8]]

3. [[4] [12] [20]]

g1=g[:,1:2,0:3:2]
print("\n",g1)
g2=g[:,0:1,:]
print("\n",g2)
g3=g[:1,:,3:]
print("\n",g3)
[[[ 9 11]]
[[13 15]]]

[[[1 2 3 4]]

[[5 6 7 8]]]

[[[ 4]
[12]
[20]]]

Sum of 3D matrices

Multiplcation of two 3D matrices

Two 30-Matrices can be multiplied if

1. they have same number of layers


2. the number of columns of first matrix is equal to the number
of rows of second matrix.
np.matmul(matrix1,matrix2)
print(d)
[[[ 1 2 3 4]
[ 5 6 7 8]]

[[ 9 10 11 12]
[13 14 15 16]]
[[17 18 19 20]
[21 22 23 24]]]
T = np.random.randint(0, 10, size=(3, 4, 2))
print(T)

[[[9 9]
[3 1]
[7 7]
[2 7]]

[[5 5]
[0 8]
[1 2]
[5 8]]
[[1 9]
[5 7]
[9 4]
[5 8]]]
m1=np.matmul(d,T)
print(m1)

[[[ 44 60]
[128 156]]

[[116 243]
[160 335]]
[[378 515]
[458 627]]]

Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE

Date: 19/11/24

Topic: Partial Differentiation


import sympy as sp

Find the partial derivative of f ( x , y )=exy.


x,y=sp.symbols('x y')
f1=sp.exp(x*y)
print("The function f1 is: ", f1)
derx_f1=sp.diff(f1,x)
print("The derivative of f1 wrt x is: ", derx_f1)
dery_f1=sp.diff(f1,y)
print("The derivative of f1 wrt y is: ", dery_f1)
The function f1 is: exp(x*y)
The derivative of f1 wrt x is: y*exp(x*y)
The derivative of f1 wrt y is: x*exp(x*y)
derx_f1=f1.diff(x)
dery_f1=f1.diff(y)
print("The derivative of f1 wrt x is: ",derx_f1)
print("The derivative of f1 wrt y is: ",dery_f1)
The derivative of f1 wrt x is: y*exp(x*y)
The derivative of f1 wrt y is: x*exp(x*y)
derxx_f1=sp.diff(derx_f1,x)
print("The double derivative of f1 wrt x is:" , derxx_f1)
deryy_f1=sp.diff(dery_f1,y)
print("The double derivative of f1 wrt y is:" , deryy_f1)
derxy_f1=sp.diff(dery_f1,x)
print("The double derivative of f1 wrt xy is:" , derxy_f1)
deryx_f1=sp.diff(derx_f1,y)
print("The double derivative of f1 wrt yx is:" , deryx_f1)
if (derxy_f1==deryx_f1): print("True") else:
print("False")
The double derivative of f1 wrt x is: y**2*exp(x*y)
The double derivative of f1 wrt y is: x**2*exp(x*y)
The double derivative of f1 wrt xy is: x*y*exp(x*y) + exp(x*y)
The double derivative of f1 wrt yx is: x*y*exp(x*y) + exp(x*y)
True
#To find higher order derivatives
derxx_f1=sp.diff(f1,x,2)
deryy_f1=sp.diff(f1,y,2)
derxy_f1=sp.diff(f1,x,y)
deryx_f1=sp.diff(f1,y,x)
print("The second order partial dericative of f1 wrt x is ", derxx_f1)
print("The second order partial dericative of f1 wrt y is ", deryy_f1)
print("The second order partial dericative of f1 wrt xy is ",
derxy_f1)
print("The second order partial dericative of f1 wrt yx is ",
deryx_f1)
The second order partial dericative of f1 wrt x is y**2*exp(x*y)
The second order partial dericative of f1 wrt y is x**2*exp(x*y)
The second order partial dericative of f1 wrt xy is (x*y +
1)*exp(x*y)
The second order partial dericative of f1 wrt yx is (x*y +
1)*exp(x*y)

Find the derivatives of function f1 wrt x till fifth order. Store them in a list

derxxx_f1=sp.diff(f1,x,3)
print("The third order partial derivative of f1 wrt x is ", derxxx_f1)
derxxxx_f1=sp.diff(f1,x,4)
print("The fourth order partial derivative of f1 wrt x is ",
derxxxx_f1)

The third order partial derivative of f1 wrt x is y**3*exp(x*y)


The fourth order partial derivative of f1 wrt x is y**4*exp(x*y)
list=[] for i in
range(1,6):
derx_f1=sp.diff(f1,x,i)
list.append(derx_f1)
print(list)
[y*exp(x*y), y**2*exp(x*y), y**3*exp(x*y), y**4*exp(x*y),
y**5*exp(x*y)]
f2=sp.exp(x*2)*sp.sin(y)+sp.log(x**2)*sp.cos(y)
print("The function f2 is: ", f2)
derx_f2=sp.diff(f2,x)
print("The derivative of f2 wrt x is: ", derx_f2)
dery_f2=sp.diff(f2,y)
print("The derivative of f2 wrt y is: ", dery_f2)
derxx_f2=sp.diff(derx_f2,x)
print("The double derivative of f2 wrt x is:" , derxx_f2)

deryy_f2=sp.diff(dery_f2,y)
print("The double derivative of f2 wrt y is:" , deryy_f2)
derxy_f2=sp.diff(dery_f2,x)
print("The double derivative of f2 wrt xy is:" , derxy_f2)
deryx_f2=sp.diff(derx_f2,y)
print("The double derivative of f2 wrt yx is:" , deryx_f2)
if (derxy_f2==deryx_f2): print("True") else:
print("False")

The function f2 is: exp(2*x)*sin(y) + log(x**2)*cos(y)


The derivative of f2 wrt x is: 2*exp(2*x)*sin(y) + 2*cos(y)/x
The derivative of f2 wrt y is: exp(2*x)*cos(y) - log(x**2)*sin(y)
The double derivative of f2 wrt x is: 4*exp(2*x)*sin(y) -
2*cos(y)/x**2
The double derivative of f2 wrt y is: -exp(2*x)*sin(y) -
log(x**2)*cos(y)
The double derivative of f2 wrt xy is: 2*exp(2*x)*cos(y) - 2*sin(y)/x
The double derivative of f2 wrt yx is: 2*exp(2*x)*cos(y) - 2*sin(y)/x
True

f3=(x**3-y)/(x**2+y**2)
print("The function f3 is: ", f3)
derx_f3=sp.diff(f3,x)
print("The derivative of f3 wrt x is: ", derx_f3)
dery_f3=sp.diff(f3,y)
print("The derivative of f3 wrt y is: ", dery_f3)
derxx_f3=sp.diff(derx_f3,x)
print("The double derivative of f3 wrt x is:" , derxx_f3)
deryy_f3=sp.diff(dery_f3,y)
print("The double derivative of f3 wrt y is:" , deryy_f3)
derxy_f3=sp.diff(dery_f3,x)
print("The double derivative of f3 wrt xy is:" , derxy_f3)
deryx_f3=sp.diff(derx_f3,y)
print("The double derivative of f3 wrt yx is:" , deryx_f3)
if (derxy_f3==deryx_f3): print("True") else:
print("False")

The function f3 is: (x**3 - y)/(x**2 + y**2)


The derivative of f3 wrt x is: 3*x**2/(x**2 + y**2) - 2*x*(x**3 -
y)/(x**2 + y**2)**2
The derivative of f3 wrt y is: -2*y*(x**3 - y)/(x**2 + y**2)**2 -
1/(x**2 + y**2)
The double derivative of f3 wrt x is: -12*x**3/(x**2 + y**2)**2 +
8*x**2*(x**3 - y)/(x**2 + y**2)**3 + 6*x/(x**2 + y**2) - 2*(x**3 -
y)/(x**2 + y**2)**2
The double derivative of f3 wrt y is: 8*y**2*(x**3 - y)/(x**2 +
y**2)**3 + 4*y/(x**2 + y**2)**2 - 2*(x**3 - y)/(x**2 + y**2)**2
The double derivative of f3 wrt xy is: -6*x**2*y/(x**2 + y**2)**2 +
8*x*y*(x**3 - y)/(x**2 + y**2)**3 + 2*x/(x**2 + y**2)**2
The double derivative of f3 wrt yx is: -6*x**2*y/(x**2 + y**2)**2 +
8*x*y*(x**3 - y)/(x**2 + y**2)**3 + 2*x/(x**2 + y**2)**2
True
Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE

Date: 20/11/24

Topic: Jacobian and euler's theorem

#Jacobian for transformations in two variables


import sympy as sp x,y=sp.symbols('x y')
f1=x**2+y f2=x*y
F=sp.Matrix([f1,f2])
Jacobian=F.jacobian([x,y])
print("Jacobian matrix is: ",Jacobian) print("The
determinant of the jacobian matrix is:
",sp.simplify(sp.det(Jacobian)))
Jacobian matrix is: Matrix([[2*x, 1], [y, x]])
The determinant of the jacobian matrix is: 2*x**2 - y
#Jacobian for transformations in three variables
import sympy as sp x,y,z=sp.symbols('x y z')
f1=x**2+y*z f2=x*y+z f3=x-y*z
F=sp.Matrix([f1,f2,f3])
Jacobian=F.jacobian([x,y,z])
print("Jacobian matrix is: ",Jacobian)
det=sp.det(Jacobian)
print("The determinant
Jacobian matrix of the jacobian
is: Matrix([[2*x, matrix
z, y], [y, is: ",sp.simplify(det))
x, 1], [1, -z, -y]])
print(det.subs(x,2).subs(y,1).subs(z,3))
The determinant of the jacobian matrix is: -2*x**2*y - x*y + 2*x*z +

z
5

import sympy as sp
r,Θ=sp.symbols('r Θ')
f1=r*sp.cos(Θ)
f2=r*sp.sin(Θ)
F=sp.Matrix([f1,f2])
Jacobian=F.jacobian([r,Θ])
print("Jacobian matrix is: ",Jacobian)
det=sp.det(Jacobian)
print("The determinant of the jacobian matrix is: ",sp.simplify(det))
Jacobian matrix is: Matrix([[cos(Θ), -r*sin(Θ)], [sin(Θ), r*cos(Θ)]])
The determinant of the jacobian matrix is: r
eulers

import sympy as sp
x,y,a=sp.symbols('x y a')
f=(x*y*2-y*3)/(x+y)
f=sp.simplify(f) print(f)
f_sym=f.atoms(sp.Symbol)
print(f_sym)

f1=f for i in
f_sym:
f1=f1.replace(i,a*i)
f1=sp.simplify(f1)
print(f1)
r=sp.rem(f1,f) if r==0:
print(f"f is homo")
q=sp.quo(f1,F)
print(q) else:
print(f"f is hetero")
print(r)
y*(2*x - 3)/(x + y)
{x, y}
y*(2*a*x - 3)/(x + y)
f is hetero
3*a*y/(x + y) - 3*y/(x + y)
import sympy as sp

x,y,a=sp.symbols('x y a')

f=(x*y*2-y*3)/(x+y)

f=sp.simplify(f) print(f)

f_sym=f.atoms(sp.Symbol)

print(f_sym)

f1=f
for i in f_sym:

f1=f1.replace(i,a*i)

f1=sp.simplify(f1)

print(f1)

f1 = sp.simplify(f1)

r=sp.rem(f1,f)

if r==0:

print(f"f is homo")

q=sp.quo(f1,f)

print(q) else:

print(f"f is hetero")
print(r)
y*(2*x - 3)/(x + y)
{x, y}
y*(2*a*x - 3)/(x + y)
f is hetero
3*a*y/(x + y) - 3*y/(x + y)
#euler's theorem import
sympy as sp
x,y,a=sp.symbols('x y a')
f=(x*y**2-y**3)/(x+y)
f=sp.simplify(f) print(f)
f_sym=f.atoms(sp.Symbol)
print(f_sym)

f1=f
print("checking the function for homogeneity")
for i in f_sym: f1=f1.replace(i,a*i)
f1=sp.simplify(f1) print(f1)
r=sp.rem(f1,f)
print(f"remainder {f1} by {f} is: {r}")
print(f"type of f1,f,r: {type(f1),type(f),type(r)}") #sp.simpify
if r==0: print("function is homogeneous") q=sp.quo(f1,f)
print(f"quotient is {q}") if
q.is_Pow and q.as_base_exp()[1]<0:
deg_homo=q.as_base_exp()[1] else:
deg_homo=sp.degree(q,a)
d_f_x=sp.diff(f,x) d_f_y=sp.diff(f,y)
lhs=sp.simplify(x*d_f_x+y*d_f_y)
rhs=sp.simplify(deg_homo*f) if
(sp.Eq(lhs,rhs)): print("eulers
theorem satisfied") else:
print("not satisfied") else:
print("function is not homogeneous")

y**2*(x - y)/(x + y)
{x, y}
checking the function for homogeneity
a**2*y**2*(x - y)/(x + y)
remainder a**2*y**2*(x - y)/(x + y) by y**2*(x - y)/(x + y) is: 0
type of f1,f,r: (<class 'sympy.core.mul.Mul'>, <class
'sympy.core.mul.Mul'>, <class 'sympy.core.numbers.Zero'>)
function is homogeneous
quotient is a**2 eulers
theorem satisfied

import sympy as sp
x,y,a=sp.symbols('x y a')
f=(x*y*2-y*3)/(x+y)
f=sp.simplify(f) print(f)
f_sym=f.atoms(sp.Symbol)
print(f_sym)

f1=f for i in f_sym:


f1=f1.replace(i,a*i)
f1=sp.simplify(f1)
print(f1)
#The line below was causing the error. It was intended to simplify the
expression f1 further.
#f1.sp.simplify(f1)
f1 = sp.simplify(f1) #Corrected line: Directly apply sp.simplify to
f1.
print(f1)
r=sp.rem(f1,f) #Also corrected this line: You probably intended to
use f instead of F here, given the context. if r==0: print(f"f is
homo") q=sp.quo(f1,f) print(q) else: print(f"f is hetero")
print(r)
y*(2*x - 3)/(x + y)
{x, y}
y*(2*a*x - 3)/(x + y)
y*(2*a*x - 3)/(x + y)
f is hetero
3*a*y/(x + y) - 3*y/(x + y)
Name: Amarjeet

Roll no: 2410996612

Branch: BE-EE with minor CSE

Date: 23/11/24

Topic: Taylor's expansion and maxima , minima

import sympy as sp
x,y,z=sp.symbols('x y z') f = input
("Enter a function : ") print("The
entered function is : ",f)
print(type(f)) f1=sp.sympify(f)
print("The changed function is : ", f1)
print(type(f1))

Enter a function : (x*y**2+y**3)/(x+y)


The entered function is : (x*y**2+y**3)/(x+y)
<class 'str'>
The changed function is : (x*y**2 + y**3)/(x + y)
<class 'sympy.core.mul.Mul'>
import sympy as sp
x,y=sp.symbols('x y')
f=sp.exp(x+y)
print(f) a=1 b=1
#approx point a,b
taylors_approx=f.series(x,a,3).removeO().series(y,b,3).removeO()
print(taylors_approx)
#at point a,b - replace series by subs
#print(sp.simplify(taylors_approx).subs(x,x0).subs(y,y0))
exp(x + y)
x*exp(2) + (x - 1)**2*exp(2)/2 + (y - 1)**2*(x*exp(2)/2 + (x -
1)**2*exp(2)/4) + (y - 1)*(x*exp(2) + (x - 1)**2*exp(2)/2)

import sympy as sp
x,y=sp.symbols('x y')
f=(x**3*y**2)*(1-x-y)
print(f)

x**3*y**2*(-x - y + 1)

#MAXIMA AND MINIMA

1. import sympy

2. define the symbols


3. get a function from the user

4. define the point around which the expansion

5. differentiate this function partially wrt x and y and put derivatives equal to zero

6. solve both these equations in terms of x and y to obtain the critical points

import sympy as sp x, y =
sp.symbols('x y')
f=input("enter a function: ")
f1=sp.sympify(f)
print("The entered function is :",f)
print("The sympified function is :",f1)
eq1=f1.diff(x) eq2=f1.diff(y)
print("The first order derivative w.r.t.x :",eq1)
print("The first order derivative w.r.t y :",eq2)
print("Solve the first order equations to obtain critical points")
solutions = sp.solve([eq1, eq2], [x, y]) print("\nThe solutions
are:", solutions) real_solutions = [] for sol in solutions: if
sol[0].is_real and sol[1].is_real:
real_solutions.append(sol)
print("The critical points are categorized using the second
derivative:", real_solutions)
print("i.e. the signs of rt-s^2 and r determine the category")
D= eq1.diff(x)*eq2.diff(y)-(eq1.diff(y))**2 print("rt-s^2
=",D) R=eq1.diff(x) print("r =",R) for sol in
real_solutions: print("\nThe real solutions are x=",
sol[0],"y=",sol[1]) d=D.subs(x,sol[0]).subs(y,sol[1])
print("rt-s^2 =",d)
r=R.subs(x,sol[0]).subs(y,sol[1])
print("r =",r) if d<0:
print("It is a saddle point")
elif d>0:
mm=f1.subs(x,sol[0]).subs(y,sol[1])
if r<0:
print("It is a local maxima",mm)
else: print("It is a local
minima",mm)

enter a function: x**3+y**3-(3*x*y)


The entered function is : x**3+y**3-(3*x*y)
The sympified function is : x**3 - 3*x*y + y**3
The first order derivative w.r.t.x : 3*x**2 - 3*y
The first order derivative w.r.t y : -3*x + 3*y**2
Solve the first order equations to obtain critical points

The solutions are: [(0, 0), (1, 1), ((-1/2 - sqrt(3)*I/2)**2, -1/2 -
sqrt(3)*I/2), ((-1/2 + sqrt(3)*I/2)**2, -1/2 + sqrt(3)*I/2)]
The critical points are categorized using the second derivative: [(0,
0), (1, 1)]
i.e. the signs of rt-s^2 and r determine the category
rt-s^2 = 36*x*y - 9
r = 6*x

The real solutions are x= 0 y= 0


rt-s^2 = -9 r = 0 It
is a saddle point

The real solutions are x= 1 y= 1


rt-s^2 = 27
r = 6
It is a local minima -1

You might also like