0% found this document useful (0 votes)
17 views76 pages

Scientific Programming Lab Manual Final 260225

The document is a manual for a Scientific Programming Lab course for first-year students, covering Python and MATLAB/GNU Octave programming. It includes installation instructions, programming basics, control structures, data structures, algorithm complexity, numerical methods, and machine learning applications. Additionally, it provides guidance on project work and report preparation.

Uploaded by

Jaya Jones
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)
17 views76 pages

Scientific Programming Lab Manual Final 260225

The document is a manual for a Scientific Programming Lab course for first-year students, covering Python and MATLAB/GNU Octave programming. It includes installation instructions, programming basics, control structures, data structures, algorithm complexity, numerical methods, and machine learning applications. Additionally, it provides guidance on project work and report preparation.

Uploaded by

Jaya Jones
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

BE FIRST YEAR II SEM

A.Y 24-25
LAB CODE: ES353CS
LAB NAME : SCIENTIFIC PROGRAMMING LAB
MANUAL
Compiled from web resources
BY
1.Dr.P.Vishvapathi,DCET
2.Dr.Uma N.Dulhare,MJCET
3.Dr.L.Raghavendar Raju,MECS

1
2
INDEX
SNO CONTENT PAGE NO.
1 Python and MATLAB/GNU OCTAVE installation IDE 4
2 Writing simple Python and MATLAB Programs 5
3 Implementing Control Structures and Functions 8
4 Implementing Data Structures in Python and MATLAB 15
5 Writing and Testing Search and Sort Algorithms 28
6 Analyzing Algorithm Complexity in Practical Problems 33
7 Implementing Numerical Methods in Python and 34
MATLAB
8 Performing Matrix Operations and Solving Linear 39
Systems
9 Case Studies and Applications in Engineering 43
10 Data Manipulation and Analysis using Pandas and 46
MATLAB
11 Creating Various Plots(Line,Scatter,Bar,Histogram) 57
12 Customizing and Interpreting Plots for Engineering 61
Data
13 Implementing Basic Machine Learning Algorithms in 65
Python
14 Exploring IoT and Big Data Tools 70
15 Working on Individual/Group Projects
16 Preparing Project Reports and Presentations 73
17 Final Projection Presentation

3
PROGRAM 1:Python and MATLAB/GNU OCTAVE installation and IDE Setup
Python Installation & IDESetup

a. Installing Python

1. DownloadPython:
o Go to the official Pythonwebsite.
o Download the latest stable version for your operating system
(Windows,macOS, or Linux).
2. Install Python:
o Run the installer.
o On Windows,ensure you select the option "Add Python to
P ATH" during installation (very important).
o Follow the installation prompts for your operating system.
3. Verify Installation:
o Open a terminal(Command Prompt on Windows or Terminal on
macOS/Linux).
o Type python--version(or python3--version on macOS/Linux) to
confirm the installation.

b. Installing an IDE for Python: Visual Studio Code(VSCode):


o Download VSCode: Go to VSCode Download.
o Install:Follow thep rompts based on your operating system.
o PythonExtension:After installation, open VSCode and goto the
Extensions Marketplace (or press Ctrl+Shift+X), search for the
Python extension by Microsoft, and install it.
o Interpreter Setup: Ensure you select the correct Python
interpreter by opening the Command Palette(Ctrl+Shift+P),typing
Python:Select Interpreter, and choosing the one you just
installed.

MATLAB Installation &IDE Setup-Most basic MATLAB syntax and built-in


functions are supported by open source GNU OCTAVE. So GNU Octave is used in
place of MATLAB: GNU OCTAVE INSTALLATION Windows
 Go to the official Octave website:
https://www.gnu.org/software/octave/download.html
 Under the Windows section, click the download link for the latest version.
 Once downloaded, run the installer (.exe file).
 Follow the installation prompts (keep default settings unless needed).
 After installation, launch Octave from the Start menu.
Verify Installation After installing, open a terminal or command prompt and
type: octave --version,If Octave is installed correctly, it will display the installed
version.
4
PROGRAM 2: Writing simple Python and MATLAB Programs
Simple Python Programs RUN USING VSCODE IDE

Hello,World!
#Asimpleprogramtoprint"Hello,World!" print("Hello, World!")
OUTPUT: Hello,World!

Sum of Two Numbers


#A simple program to calculate the sum of two numbers
num1 = 5
num2=10
sum=num1+num2
print(f"The sum of {num1} and {num2} is {sum}.")
OUTPUT: The sum of 5 and 10 is 15.

Even or Odd Number


#A simple program to check if a number is even or odd
num = int(input("Enter a number: "))
ifnum%2==0:
print(f"{num} is an even number.")
else:
print(f"{num} is an odd number.")
OUTPUT: Enter a number: 5
5 is an odd number

Factorial of a Number
#A program to find the factorial of a number
num= int(input("Enter a number to find its factorial:"))
factorial = 1
for i in range(1,num+1):
factorial *= i
print(f"The factorial of {num} is {factorial}.")
OUTPUT: Enter a number to find its factorial: 5
The factorial of 5 is 120.

Fibonacci Sequence
#A program to print the Fibonacci sequence up to n terms
n=int(input("Enter the number of terms in the Fibonacci sequence:"))
a, b = 0, 1
print("Fibonacci sequence:")
for _ in range(n):
print(a,end="")
a, b = b, a + b
5
OUTPUT: Enter the number of terms in the Fibonacci sequence: 9
Fibonacci sequence: 0 1 1 2 3 5 8 13 21

Simple MATLAB Programs can be executed using GNU OCTAVE.


Open a new file and enter the below script and run it and the output will be
displayed in the command window.

Hello,World!
%A simple program to display"Hello,World!"
disp('Hello, World!')
OUTPUT:Hello, World!

Sum of Two Numbers


%A program to calculate the sum of two numbers
num1 = 5;
num2=10;
sum=num1+ num2;
fprintf('The sum of %d and %d is %d.\n',num1,num2,sum);
OUTPUT: The sum of 5 and 10 is 15.
Even or Odd Number
%A program to check if a number is even or odd
num = input('Enter a number: ');
if mod(num,2)==0
fprintf('%d is an even number.\n',num);
else
fprintf('%d is an odd number.\n',num);
end
OUTPUT: 'Enter a number: 5
5 is an odd number

Factorial of a Number
%A program to find the factorial of a number
num=input('Enter a number to find its factorial:');
factorial = 1;
fori=1:num
factorial=factorial* i;
end
fprintf('The factorial of %d is %d.\n',num,factorial);
OUTPUT: Enter a number to find its factorial: 5
The factorial of 5 is 120.

6
Fibonacci Sequence
%A program to print the Fibonacci sequence up to n terms
n=input('Enter the number of terms in the Fibonacci sequence:');
a=0;
b=1;
fprintf('Fibonacci sequence:\n'); for
i = 1:n
fprintf('%d',a);
temp = a + b;
a=b;
b=temp;
end
fprintf('\n');
OUTPUT: Enter the number of terms in the Fibonacci sequence: 8
Fibonacci sequence: 0 1 1 2 3 5 8 13

7
PROGRAM 3: Implementing control structures and functions
Python Program Using if-else(Conditional Statement)

GradeEvaluation : This program takes a student's score as input and evaluates


the grade based on the score.

#A program to evaluate a student's grade based on score


score = int(input("Enter the score (0-100): "))
if score >= 90:
print("Grade:A")
elif score >= 80:
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
else:
print("Grade:F")
OUTPUT: Enter the score (0-100): 90
Grade: A
Python Program Using for Loop : Multiplication Table

#A program to print the multiplication table of a number


num=int(input("Enter a number to generate its multiplication table:"))
print(f"Multiplication tableof{num}:")
for i in range(1, 11):
print(f"{num}x{i}={num*i}")
OUTPUT: Enter a number to generate its multiplication table: 9
Multiplication table of 9:
9x1=9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90

8
Python Program Using while Loop : This program counts down from a given
number to zero using a while loop.

#A program to count down from a given number


num=int(input("Enter a number to count down: "))
whilenum>=0:
print(num)
num -= 1
Enter a number to countdown: 9
9
8
7
6
5
4
3
2
1
0

Python Program Using Nested Loops : Multiplication Table(Nested Loops)

This program prints the multiplication table in a grid format using nested loops.
num = int(input("Enter a number to generate its multiplication table: "))
# Using nested for loops to generate the multiplication table
print(f"\nMultiplication Table of {num}:\n")
for i in range(1, 11): # Outer loop for numbers 1 to 10
for j in range(1, 11): # Inner loop for numbers 1 to 10
result = i * j
print(f"{i} x {j} = {result}")
print("-" * 20) # Separating each row for better readability
OUPUT: Enter a number to generate its multiplication table: 5
Multiplication Table of 5:
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5
1x6=6
1x7=7
9
1x8=8
1x9=9
1 x 10 = 10
--------------------
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
--------------------
...
MATLAB program that demonstrates the use of if-else conditional statements
% Check if the number is positive, negative, or zero
num = input('Enter a number: ');
if num > 0
disp('The number is positive.');
elseif num < 0
disp('The number is negative.');
else
disp('The number is zero.');
end
OUTPUT: Enter a number: 5
The number is positive.
MATLAB program that demonstrates the use of a while loop.
In this example, the program will print numbers from 1 to 10
counter = 1;
% While loop to print numbers from 1 to 10
while counter <= 10
disp(counter);
counter = counter + 1;
% Increment the counter by 1
end
OUTPUT:
1
2
3
4
10
5
6
7
8
9
10
MATLAB program that generates a multiplication table using nested loops:
num = input('Enter a number to generate its multiplication table: ');
% Using nested loops to generate the multiplication table
fprintf('\nMultiplication Table of %d:\n', num);
fori = 1:10 % Outer loop for numbers 1 to 10
forj = 1:10 % Inner loop for numbers 1 to 10
result = i * j;
fprintf('%d x %d = %d\n', i, j, result);
% Print the resultend fprintf('-------------------------\n');
% Separator for better readability
end
OUPUT:
Enter a number to generate its multiplication table: 5
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5
1x6=6
1x7=7
1x8=8
1x9=9
1 x 10 = 10
--------------------
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
--------------------
...
11
Implementing Functions in Python

Basic Function Without Parameters


Hello,World!Function: This function simply prints"Hello,World!"when called.
#A simple function that prints Hello,World!
def greet():
print("Hello,World!")
#Calling the function
greet()
OUTPUT: Hello, World!

Function with Parameters : Addition Function: This function takes two


numbers as parameters and returns their sum.

#A function that adds two numbers


def add(a, b):
result=a+b
return result

#Calling the function with arguments


num1 = 5
num2=10
print(f"The sum of {num1} and {num2} is: {add(num1,num2)}")
OUTPUT: The sum of 5 and 10 is: 15

Function with Multiple Return Values: Basic Math Operations

This function performs multiple operations(addition,subtraction,


multiplication)on two numbers and returns the results.

#A function that returns multiple values(sum,difference,andproduct)


def basic_operations(a, b):
sum_result=a+b
difference=a-b
product = a * b
return sum_result,difference,product
#Calling the function and unpacking the returned values
a=8
b=4
sum_res,diff,prod=basic_operations(a,b)
print(f"Sum: {sum_res}")
print(f"Difference:{diff}")

12
print(f"Product: {prod}")
OUTPUT: Sum: 12
Difference: 4
Product: 32

Function with Recursion: Factorial Using Recursion

#A function to calculate the factorial of a number using recursion


def factorial(n):
if n==0 or n==1: #Basecase
return 1
else:
return n*factorial(n-1)
#Calling the function
num = 5
print(f"The factorial of {num} is: {factorial(num)}")
OUTPUT: The factorial of 5 is: 120

Implementing Functions in MATLAB

Function to Calculate the Square of a Number


% square Number function: This function returns the square of a number
function result = squareNumber(num)
result = num^2; % Square the input number
end

% Main script that calls the square Number function


% Ask the user for a number
num = input('Enter a number to calculate its square: ');
% Call the function and display the result
result = squareNumber(num);
fprintf('The square of %.2f is %.2f.\n', num, result);

OUTPUT: Enter a number to calculate its square: 5


The square of 5.00 is 25.00.

Function to Calculate Factorial of a Number


% factorial Number function: This function calculates the factorial of a number
function result = factorialNumber(num)
result = 1; % Initialize result as 1
for i = 1:num
result = result * i; % Multiply result by each number up to num
end
end
13
% Main script that calls the factorialNumber function
% Ask the user for a number
num = input('Enter a number to calculate its factorial: ');
% Call the function and display the result
result = factorialNumber(num);
fprintf('The factorial of %d is %d.\n', num, result);

OUTPUT: Enter a number to calculate its factorial: 5


The factorial of 5 is 120.

Function to Find the Largest of Three Numbers


% find Largest function: Returns the largest of three numbers
function largest = findLargest(a, b, c)
if a >= b && a >= c
largest = a;
elseif b >= a && b >= c
largest = b;
else
largest = c;
end
end
% Main script that calls the findLargest function
% Ask the user for three numbers
a = input('Enter the first number: ');
b = input('Enter the second number: ');
c = input('Enter the third number: ');
% Call the function and display the result
largest = findLargest(a, b, c);
fprintf('The largest number among %.2f, %.2f, and %.2f is %.2f.\n', a, b, c,
largest);

Enter the first number: 5


Enter the second number: 3
Enter the third number: 8
The largest number among 5.00, 3.00, and 8.00 is 8.00.

14
PROGRAM 4 : Implementing Data Structures in Python and MATLAB
Data Structures in Python
Lists(Array-like Structure) : This program demonstrate to create, update, and
manipulate lists.

#Create a list
fruits=['apple','banana','cherry']
#Add an item to the list
fruits.append('orange')

#Insert an item at a specific position


fruits.insert(1, 'kiwi')

#Remove an item from the list


fruits.remove('banana')
#Accessing elements
print(f"The first fruitis:{fruits[0]}")

#Slicing the list


print(f"Fruits from index 1to2:{fruits[1:3]}")
#Loop through the list
for fruit in fruits:
print(fruit)

OUTPUT:
The first fruit is: apple
Fruits from index 1 to 2: ['kiwi', 'cherry']
apple
kiwi
cherry
orange

15
Stack(LIFO:Last In,First Out): Stack Implementation Using a List
class Stack:
def __init__(self): # Fixed: __init__ should be used
self.stack = []

def push(self, item):


self.stack.append(item)

def pop(self):
if self.is_empty():
return "Stack is empty"
return self.stack.pop()

def peek(self):
if self.is_empty():
return "Stack is empty"
return self.stack[-1]

def is_empty(self):
return len(self.stack) == 0

def size(self):
return len(self.stack)

# Using the Stack


my_stack = Stack()

my_stack.push(10)
my_stack.push(20)
my_stack.push(30)

print(f"Top of the stack: {my_stack.peek()}") # The top of the stack should be 30


print(f"Stack size: {my_stack.size()}") # The size should be 3
print(f"Popped item: {my_stack.pop()}") # It will pop 30
print(f"Stack size after pop: {my_stack.size()}") # The size will now be 2
OUTPUT: Top of the stack: 30
Stack size: 3
Popped item: 30
Stack size after pop: 2

16
Queue(FIFO:First In,First Out)
class Queue:
def __init__(self):
self.queue = [] # Initialize an empty list to represent the queue

def enqueue(self, item):


"""Add an item to the end of the queue."""
self.queue.append(item)

def dequeue(self):
"""Remove and return the item from the front of the queue."""
if self.is_empty():
return "Queue is empty"
return self.queue.pop(0) # Remove and return the first item in the list

def peek(self):
"""Return the front item without removing it."""
if self.is_empty():
return "Queue is empty"
return self.queue[0]

def is_empty(self):
"""Check if the queue is empty."""
return len(self.queue) == 0

def size(self):
"""Return the number of items in the queue."""
return len(self.queue)
# Using the Queue
my_queue = Queue()
# Enqueue some items
my_queue.enqueue(10)
my_queue.enqueue(20)
my_queue.enqueue(30)

17
print(f"Front of the queue: {my_queue.peek()}") # The front item should be 10
print(f"Queue size: {my_queue.size()}") # The size should be 3
print(f"Dequeued item: {my_queue.dequeue()}") # It will dequeue 10
print(f"Queue size after dequeue: {my_queue.size()}") # The size will now be 2
print(f"Front of the queue after dequeue: {my_queue.peek()}") # Now it should
be 20

OUTPUT:
Front of the queue: 10
Queue size: 3
Dequeued item: 10
Queue size after dequeue: 2
Front of the queue after dequeue: 20

Dictionary (HashMap) Program in Python : In Python, dictionaries are used to


store key-value pairs, and they behave like hash maps in other programming
languages. A dictionary in Python is an unordered collection of items, where
each item consists of a key and a corresponding value.

Here's a simple Python program that demonstrates how to use a dictionary (hash
map) for storing, retrieving, updating, and deleting key-value pairs:

# Create a dictionary
my_dict = {
'name': 'John',
'age': 25,
'city': 'New York'
}

# Accessing values using keys


print(f"Name: {my_dict['name']}")
print(f"Age: {my_dict['age']}")
print(f"City: {my_dict['city']}")

# Adding a new key-value pair to the dictionary

18
my_dict['job'] = 'Engineer'

# Updating an existing key-value pair


my_dict['age'] = 26

# Display the updated dictionary


print(f"Updated Dictionary: {my_dict}")

# Checking if a key exists in the dictionary


if 'name' in my_dict:
print(f"Name exists in dictionary: {my_dict['name']}")

# Removing a key-value pair from the dictionary using 'del'


del my_dict['city']

# Using the pop() method to remove a key-value pair


job = my_dict.pop('job')

# Display the removed item


print(f"Removed job: {job}")

# Display the final state of the dictionary


print(f"Final Dictionary: {my_dict}")

# Getting all keys and values


print(f"Keys: {my_dict.keys()}")
print(f"Values: {my_dict.values()}")

OUTPUT:
Name: John
Age: 25
City: New York
Updated Dictionary: {'name': 'John', 'age': 26, 'city': 'New York', 'job': 'Engineer'}
Name exists in dictionary: John

19
Removed job: Engineer
Final Dictionary: {'name': 'John', 'age': 26, 'city': 'New York'}
Keys: dict_keys(['name', 'age', 'city'])
Values: dict_values(['John', 26, 'New York'])

Data Structures in MATLAB


ARRAYS
% Create an initial array
myArray = [10, 20, 30, 40, 50];

% Accessing elements
firstElement = myArray(1); % First element
disp(['First Element: ', num2str(firstElement)]);

thirdElement = myArray(3); % Third element


disp(['Third Element: ', num2str(thirdElement)]);

% Modifying elements
myArray(2) = 25; % Update the second element
disp('Updated Array:');
disp(myArray); % Output: [10, 25, 30, 40, 50]

% Adding elements
myArray = [myArray, 60]; % Append 60 to the array
disp('Array after Adding 60:');
disp(myArray); % Output: [10, 25, 30, 40, 50, 60]

% Removing elements
myArray(2) = []; % Remove the second element (25)
disp('Array after Removing Second Element:');
disp(myArray); % Output: [10, 30, 40, 50, 60]

% Slicing arrays
subArray = myArray(2:4); % Extract elements 2 to 4

20
disp('Sliced SubArray (2 to 4):');
disp(subArray); % Output: [30, 40, 50]

% Checking if an element exists


exists = ismember(40, myArray); % Check if 40 is in the array
disp(['Does 40 exist in the array? ', num2str(exists)]); % Output: true

% Length of the array


arrayLength = length(myArray);
disp(['Length of Array: ', num2str(arrayLength)]);

% Looping through the array


disp('Looping through array elements:');
for i = 1:length(myArray)
disp(myArray(i));
end
OUTPUT:
First Element: 10
Third Element: 30
Updated Array:
10 25 30 40 50
Array after Adding 60:
10 25 30 40 50 60
Array after Removing Second Element:
10 30 40 50 60
Sliced SubArray (2 to 4):
30 40 50
Does 40 exist in the array? 1
Length of Array: 5
Looping through array elements:
10
30
40
50

21
60

STACK Implementation in MATLAB


classdef Stack
properties
stack = []; % Initialize an empty array for the stack
end

methods
% Push an item onto the stack
function push(obj, item)
obj.stack = [obj.stack, item]; % Append item to the end of the stack
end

% Pop an item from the stack


function item = pop(obj)
if ~obj.isEmpty() % Check if the stack is empty
item = obj.stack(end); % Get the last element
obj.stack(end) = []; % Remove the last element
else
item = 'Stack is empty'; % Return a message if stack is empty
end
end

% Peek at the top item of the stack


function item = peek(obj)
if ~obj.isEmpty() % Check if the stack is empty
item = obj.stack(end); % Return the top item (last element)
else
item = 'Stack is empty'; % Return a message if stack is empty
end
end

% Check if the stack is empty

22
function isEmpty = isEmpty(obj)
isEmpty = isempty(obj.stack); % True if stack is empty, false otherwise
end

% Get the size of the stack (number of elements)


function size = size(obj)
size = length(obj.stack); % Return the number of elements in the stack
end
end
end

Example Usage of the Stack Class


% Create a Stack object
myStack = Stack();

% Push elements onto the stack


myStack.push(10);
myStack.push(20);
myStack.push(30);

% Display the top element


disp(['Top element: ', num2str(myStack.peek())]); % Output: Top element: 30

% Display the size of the stack


disp(['Stack size: ', num2str(myStack.size())]); % Output: Stack size: 3

% Pop the top element


disp(['Popped element: ', num2str(myStack.pop())]); % Output: Popped
element: 30

% Display the size of the stack after popping


disp(['Stack size after pop: ', num2str(myStack.size())]); % Output: Stack size
after pop: 2

23
% Check if the stack is empty
disp(['Is the stack empty? ', num2str(myStack.isEmpty())]); % Output: Is the
stack empty? 0 (false)

% Pop all elements


disp(['Popped element: ', num2str(myStack.pop())]); % Output: Popped
element: 20
disp(['Popped element: ', num2str(myStack.pop())]); % Output: Popped
element: 10

% Check if the stack is empty


disp(['Is the stack empty now? ', num2str(myStack.isEmpty())]); % Output: Is the
stack empty now? 1 (true)

% Try popping from an empty stack


disp(['Popped element: ', myStack.pop()]); % Output: Popped element: Stack is
empty
OUTPUT:
Top element: 30
Stack size: 3
Popped element: 30
Stack size after pop: 2
Is the stack empty? 0
Popped element: 20
Popped element: 10
Is the stack empty now? 1
Popped element: Stack is empty

24
Queue Implementation in MATLAB
classdef Queue
properties
queue = []; % Initialize an empty array for the queue
end

methods
% Enqueue an item into the queue (add to the end)
function enqueue(obj, item)
obj.queue = [obj.queue, item]; % Append item to the end of the
queue
end

% Dequeue an item from the queue (remove from the front)


function item = dequeue(obj)
if ~obj.isEmpty() % Check if the queue is empty
item = obj.queue(1); % Get the first element
obj.queue(1) = []; % Remove the first element
else
item = 'Queue is empty'; % Return a message if the queue is empty
end
end

% Peek at the front item of the queue (without removing it)


function item = peek(obj)
if ~obj.isEmpty() % Check if the queue is empty
item = obj.queue(1); % Return the front item
else
item = 'Queue is empty'; % Return a message if the queue is empty
end
end

% Check if the queue is empty


function isEmpty = isEmpty(obj)

25
isEmpty = isempty(obj.queue); % True if the queue is empty, false
otherwise
end

% Get the size of the queue (number of elements)


function size = size(obj)
size = length(obj.queue); % Return the number of elements in the
queue
end
end
end

Example Usage of the Queue Class


% Create a Queue object
myQueue = Queue();

% Enqueue elements into the queue


myQueue.enqueue(10);
myQueue.enqueue(20);
myQueue.enqueue(30);

% Display the front element


disp(['Front element: ', num2str(myQueue.peek())]); % Output: Front
element: 10

% Display the size of the queue


disp(['Queue size: ', num2str(myQueue.size())]); % Output: Queue size: 3

% Dequeue the front element


disp(['Dequeued element: ', num2str(myQueue.dequeue())]); % Output:
Dequeued element: 10

% Display the size of the queue after dequeueing


disp(['Queue size after dequeue: ', num2str(myQueue.size())]); % Output:
Queue size after dequeue: 2
26
% Check if the queue is empty
disp(['Is the queue empty? ', num2str(myQueue.isEmpty())]); % Output: Is
the queue empty? 0 (false)

% Dequeue all elements


disp(['Dequeued element: ', num2str(myQueue.dequeue())]); % Output:
Dequeued element: 20
disp(['Dequeued element: ', num2str(myQueue.dequeue())]); % Output:
Dequeued element: 30

% Check if the queue is empty


disp(['Is the queue empty now? ', num2str(myQueue.isEmpty())]); % Output:
Is the queue empty now? 1 (true)

% Try dequeuing from an empty queue


disp(['Dequeued element: ', myQueue.dequeue()]); % Output: Dequeued
element: Queue is empty
OUTPUT:
Front element: 10
Queue size: 3
Dequeued element: 10
Queue size after dequeue: 2
Is the queue empty? 0
Dequeued element: 20
Dequeued element: 30
Is the queue empty now? 1
Dequeued element: Queue is empty

27
PROGRAM 5: Writing and Testing Search and Sort Algorithms
Search Algorithms in python
Linear Search and Binary Search Algorithm
def linear_search(arr, target):
for index, element in enumerate(arr):
if element == target:
return index # Return the index if the element is found
return -1 # Return -1 if the element is not found

def binary_search(arr, target):


left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2 # Find the middle element
if arr[mid] == target: # If the target is found
return mid
elif arr[mid] < target: # If the target is in the right half
left = mid + 1
else: # If the target is in the left half
right = mid - 1

return -1 # Return -1 if the element is not found


Testing the Search Algorithms
# Sample array (unsorted for linear search)
arr_unsorted = [10, 3, 5, 8, 7, 1, 9, 2]
# Sample array (sorted for binary search)
arr_sorted = sorted(arr_unsorted) # Sorting the array for binary search
target = 5

# Test Linear Search


linear_result = linear_search(arr_unsorted, target)
if linear_result != -1:
print(f"Linear Search: Target {target} found at index {linear_result}")
else:
print(f"Linear Search: Target {target} not found")

28
# Test Binary Search
binary_result = binary_search(arr_sorted, target)
if binary_result != -1:
print(f"Binary Search: Target {target} found at index {binary_result}")
else:
print(f"Binary Search: Target {target} not found")

OUTPUT:
Linear Search: Target 5 found at index 2
Binary Search: Target 5 found at index 2

Search Algorithms in MATLAB


Linear Search in MATLAB
function index = linearSearch(arr, target)
% Linear Search Algorithm
% Returns the index of the target element if found, else returns -1
index = -1; % Initialize index as -1 (not found)

for i = 1:length(arr)
if arr(i) == target
index = i; % Return the index (1-based) if element is found
return;
end
end
end
Binary Search in MATLAB
function index = binarySearch(arr, target)
% Binary Search Algorithm (requires sorted array)
% Returns the index of the target element if found, else returns -1

left = 1; % Starting index


right = length(arr); % Ending index

29
while left <= right
mid = floor((left + right) / 2); % Find the middle index

if arr(mid) == target
index = mid; % Return the index (1-based) if the element is found
return;
elseif arr(mid) < target
left = mid + 1; % If the target is larger, search in the right half
else
right = mid - 1; % If the target is smaller, search in the left half
end
end

index = -1; % Return -1 if the element is not found


end
Testing the Search Algorithms in MATLAB
% Sample array for Linear Search (unsorted)
arr_unsorted = [10, 3, 5, 8, 7, 1, 9, 2];

% Sample array for Binary Search (sorted)


arr_sorted = sort(arr_unsorted); % Sort the array for binary search

target = 5;

% Test Linear Search


linear_result = linearSearch(arr_unsorted, target);
if linear_result ~= -1
disp(['Linear Search: Target ', num2str(target), ' found at index ',
num2str(linear_result)]);
else
disp(['Linear Search: Target ', num2str(target), ' not found']);
end

% Test Binary Search

30
binary_result = binarySearch(arr_sorted, target);
if binary_result ~= -1
disp(['Binary Search: Target ', num2str(target), ' found at index ',
num2str(binary_result)]);
else
disp(['Binary Search: Target ', num2str(target), ' not found']);
end

OUTPUT:
Linear Search: Target 5 found at index 3
Binary Search: Target 5 found at index 3

SORTING ALGORITHMS IN PYTHON


Bubble Sort
def bubble_sort(arr):
n = len(arr)
for i in range(n):
# Flag to check if any swapping happened in this pass
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j] # Swap the elements
swapped = True
# If no elements were swapped, the list is already sorted
if not swapped:
break
return arr
arr = [10, 3, 5, 8, 7, 1, 9, 2]
print("Original Array:", arr)
# Test Bubble Sort
bubble_sorted = bubble_sort(arr.copy())
print("Sorted using Bubble Sort:", bubble_sorted)
Original Array: [10, 3, 5, 8, 7, 1, 9, 2]
Sorted using Bubble Sort: [1, 2, 3, 5, 7, 8, 9, 10]

31
Bubble Sort Algorithm in MATLAB
function sorted_array = bubbleSort(arr)
n = length(arr); % Get the number of elements in the array
for i = 1:n
swapped = false; % Flag to check if any swapping happens
for j = 1:n-i
if arr(j) > arr(j+1)
% Swap elements if they are in the wrong order
temp = arr(j);
arr(j) = arr(j+1);
arr(j+1) = temp;
swapped = true; % Mark that a swap has happened
end
end
% If no elements were swapped, the array is already sorted
if ~swapped
break;
end
end
sorted_array = arr; % Return the sorted array
end
% Example unsorted array
arr = [10, 3, 5, 8, 7, 1, 9, 2];
disp('Original Array:');
disp(arr);
% Call the bubbleSort function
sorted_arr = bubbleSort(arr);
disp('Sorted Array:');
disp(sorted_arr);
OUTPUT:
Original Array:
10 3 5 8 7 1 9 2
Sorted Array:
1 2 3 5 7 8 9 10

32
PROGRAM 6 : Analyzing Algorithm Complexity in Practical Problems
Bubble Sort Time Complexity in python
import time
# Bubble Sort function
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False # Flag to check if any swap was made during this pass
for j in range(n-i-1): # The last i elements are already sorted
if arr[j] > arr[j+1]:
# Swap elements if they are in the wrong order
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if not swapped:
break # No swaps were made, array is already sorted
return arr
# Example array
arr = [64, 34, 25, 12, 22, 11, 90]
# Record the start time
start_time = time.time()
# Call the bubble_sort function
sorted_arr = bubble_sort(arr)
# Record the end time
end_time = time.time()
# Calculate the time taken to sort the array
elapsed_time = end_time - start_time
# Output the results
print("Original array:", [64, 34, 25, 12, 22, 11, 90])
print("Sorted array:", sorted_arr)
print(f"Time taken to sort the array: {elapsed_time:.6f} seconds")
OUTPUT:
Original array: [64, 34, 25, 12, 22, 11, 90]
Sorted array: [11, 12, 22, 25, 34, 64, 90]
Time taken to sort the array: 0.000004 seconds

33
PROGRAM 7 : Implementing Numerical Methods in Python and MATLAB
Implementing Numerical Methods in Python
Bisection Method (Root Finding): Let's solve f(x) = x^2 - 4

def bisection_method(f, a, b, tol=1e-5, max_iter=100):


if f(a) * f(b) > 0:
print("The function must have opposite signs at the endpoints a and b.")
return None
iter_count = 0
while (b - a) / 2 > tol:
c = (a + b) / 2
if f(c) == 0: # Root is found
return c
elif f(c) * f(a) < 0:
b=c
else:
a=c
iter_count += 1
if iter_count > max_iter:
print("Maximum iterations reached.")
break
return (a + b) / 2 # Return midpoint as root approximation
# Example function: f(x) = x^2 - 4
def func(x):
return x**2 - 4
# Applying bisection method
root = bisection_method(func, 0, 3)
print(f"Root: {root}")
OUTPUT: Root: 2.000000238418579

Newton-Raphson Method (Root Finding)


def newton_raphson_method(f, f_prime, x0, tol=1e-5, max_iter=100):
x = x0
iter_count = 0
while abs(f(x)) > tol:
34
x = x - f(x) / f_prime(x)
iter_count += 1
if iter_count > max_iter:
print("Maximum iterations reached.")
break
return x
# Example function: f(x) = x^2 - 4, f'(x) = 2x
def func(x):
return x**2 - 4
def func_prime(x):
return 2*x
# Applying Newton-Raphson method
root = newton_raphson_method(func, func_prime, 3)
print(f"Root: {root}")
OUTPUT: Root: 2.000000000000002

Trapezoidal Rule (Numerical Integration)

Let's approximate the integral of f(x) = x^2 from a=0 to b=2 using the Trapezoidal
Rule with n=1000 subintervals.

def trapezoidal_rule(f, a, b, n):

h = (b - a) / n

integral = 0.5 * (f(a) + f(b)) # First and last terms

for i in range(1, n):

integral += f(a + i * h) # Middle terms

return integral * h

# Example function: f(x) = x^2

def func(x):

return x**2

35
# Applying the Trapezoidal Rule

result = trapezoidal_rule(func, 0, 2, 1000)

print(f"Integral result: {result}")

OUTPUT: Integral result: 2.666667

Implementing Numerical Methods in MATLAB


Bisection Method (Root Finding)
function root = bisection_method(f, a, b, tol, max_iter)
if f(a) * f(b) > 0
disp('The function must have opposite signs at the endpoints a and b.');
return;
end
iter_count = 0;
while (b - a) / 2 > tol
c = (a + b) / 2;
if f(c) == 0
root = c; % Root found
return;
elseif f(c) * f(a) < 0
b = c;
else
a = c;
end
iter_count = iter_count + 1;
if iter_count > max_iter
disp('Maximum iterations reached.');
break;
end
end
root = (a + b) / 2; % Midpoint is the approximate root
end

36
% Example function: f(x) = x^2 - 4
f = @(x) x^2 - 4;
% Using the bisection method
root = bisection_method(f, 0, 3, 1e-5, 100);
disp(['Root: ', num2str(root)]);
OUTPUT: Root: 2

Newton-Raphson Method (Root Finding)


function root = newton_raphson_method(f, f_prime, x0, tol, max_iter)
x = x0;
iter_count = 0;
while abs(f(x)) > tol
x = x - f(x) / f_prime(x);
iter_count = iter_count + 1;

if iter_count > max_iter


disp('Maximum iterations reached.');
break;
end
end

root = x;
end
% Example function: f(x) = x^2 - 4, f'(x) = 2x
f = @(x) x^2 - 4;
f_prime = @(x) 2*x;
% Using the Newton-Raphson method
root = newton_raphson_method(f, f_prime, 3, 1e-5, 100);
disp(['Root: ', num2str(root)]);
OUTPUT: Root: 2

Trapezoidal Rule (Numerical Integration)


function integral = trapezoidal_rule(f, a, b, n)
h = (b - a) / n; % Step size

37
integral = 0.5 * (f(a) + f(b)); % First and last terms
for i = 1:n-1
integral = integral + f(a + i * h); % Middle terms
end
integral = integral * h; % Final result
end
% Example function: f(x) = x^2
f = @(x) x^2;
% Using the Trapezoidal Rule
result = trapezoidal_rule(f, 0, 2, 1000);
disp(['Integral result: ', num2str(result)]);
OUTPUT: Integral result: 2.6667

38
PROGRAM 8 : Performing Matrix Operations and Solving Linear Systems

In Python, matrix operations and solving linear systems can be easily performed
using the numpy library.First, ensure that you have numpy installed: pip install
numpy

Matrix Operations in Python (using numpy):

import numpy as np

# Define matrices

A = np.array([[1, 2], [3, 4]])

B = np.array([[5, 6], [7, 8]])

# Matrix Addition

C_add = A + B

print("Matrix Addition:\n", C_add)

# Matrix Subtraction

C_sub = A - B

print("Matrix Subtraction:\n", C_sub)

# Matrix Multiplication (Dot Product)

C_mult = np.dot(A, B)

print("Matrix Multiplication (A * B):\n", C_mult)

# Matrix Transpose

C_transpose = A.T

print("Matrix Transpose of A:\n", C_transpose)

# Matrix Inversion

A_inv = np.linalg.inv(A)

print("Matrix Inverse of A:\n", A_inv)

39
OUTPUT:

Matrix Addition:

[[ 6 8]

[10 12]]

Matrix Subtraction:

[[-4 -4]

[-4 -4]]

Matrix Multiplication (A * B):

[[19 22]

[43 50]]

Matrix Transpose of A:

[[1 3]

[2 4]]

Matrix Inverse of A:

[[-2. 1. ]

[ 1.5 -0.5]]

Solving Linear Systems: To solve a system of linear equations, we can use


numpy.linalg.solve(), which is a convenient way to solve the equation Ax = b
for x, where A is the coefficient matrix and b is the right-hand side vector.

Consider the system of linear equations:

2x + y = 5

x + 2y = 6

This system can be represented in matrix form as:

A = [[2, 1], [1, 2]]

40
b = [5, 6]

import numpy as np

# Coefficient matrix (A)

A = np.array([[2, 1], [1, 2]])

# Right-hand side (b)

b = np.array([5, 6])

# Solve for x (where Ax = b)

x = np.linalg.solve(A, b)

print("Solution (x, y):", x)

OUTPUT: Solution (x, y): [1. 3.]

Determinant and Rank of a Matrix: ou can also compute the determinant and
rank of a matrix using numpy.linalg.det() and numpy.linalg.matrix_rank().

# Determinant of matrix A

det_A = np.linalg.det(A)

print("Determinant of A:", det_A)

# Rank of matrix A

rank_A = np.linalg.matrix_rank(A)

print("Rank of A:", rank_A)

OUTPUT: Determinant of A: 3.0000000000000004

Rank of A: 2

Eigenvalues and Eigenvectors

# Eigenvalues and Eigenvectors of A

eigenvalues, eigenvectors = np.linalg.eig(A)

41
print("Eigenvalues:", eigenvalues)

print("Eigenvectors:\n", eigenvectors)

OUTPUT: Eigenvalues: [ 5. -0. ]

Eigenvectors:

[[ 0.70710678 -0.70710678]

[ 0.70710678 0.70710678]]

42
PROGRAM 9 : Case Studies and Applications in Engineering

Scientific programming is crucial in engineering to model complex systems,


simulate physical processes, solve differential equations, optimize designs, and
analyze large datasets. Below are some examples of scientific programming
applications in engineering, along with the case studies illustrating their use.

Finite Element Analysis (FEA) for Structural Engineering


Problem: Structural Integrity of a Beam Under Load

Application: Finite Element Analysis (FEA) is used to simulate the behavior of a


structure (like a beam) under different loads and conditions. The goal is to
determine stress, strain, and displacement patterns in the structure.

Steps Involved:

1. Problem Definition: Model the beam as a collection of elements (nodes and


finite elements).
2. Mesh Generation: Divide the beam into smaller elements (discretization).
3. Material Properties: Define material properties like Young's modulus,
Poisson's ratio, and density.
4. Boundary Conditions: Apply boundary conditions (fixed or free ends, loads).
5. Solver: Use numerical solvers (like Gaussian elimination) to solve the system
of equations that govern the system's behavior.
6. Post-Processing: Visualize the displacement, stress, and strain distributions.

Scientific Programming Tools:

 Languages: Python, MATLAB, C++


 Libraries: FEniCS (Python), ABAQUS, ANSYS

Computational Fluid Dynamics (CFD) for Flow Simulation


Problem: Fluid Flow Over an Airfoil

Application: Computational Fluid Dynamics (CFD) is used to analyze the behavior


of fluid flows around objects (e.g., airfoils, pipes). For this example, the flow over
an airfoil needs to be simulated to evaluate its lift and drag forces.

Steps Involved:

1. Geometry Creation: Model the airfoil geometry.


2. Mesh Generation: Discretize the geometry into cells (e.g., using a
structured or unstructured grid).
3. Governing Equations: Solve the Navier-Stokes equations for fluid dynamics.
43
4. Boundary Conditions: Set inlet, outlet, and wall boundary conditions for the
flow.
5. Solver: Use numerical solvers to compute velocity, pressure, and other
parameters at each cell.
6. Post-Processing: Visualize the velocity field, pressure distribution, and
forces acting on the airfoil.

Scientific Programming Tools:

 Languages: Python, MATLAB, C++


 Libraries: OpenFOAM, CFDTool (MATLAB), PyFoam (Python)

Control Systems Design for a Mechanical System


Problem: Designing a PID Controller for a Motor Speed Control System

Application: In mechanical engineering, controlling the speed of a motor is a


common problem. The task is to design a PID controller that ensures the motor
speed follows a desired reference value while minimizing the error.

Steps Involved:

1. Modeling the System: Create a mathematical model for the motor (e.g.,
transfer function or state-space model).
2. Controller Design: Design a PID controller (Proportional-Integral-Derivative
controller) to regulate motor speed.
3. Simulation: Simulate the system response to step or ramp inputs, and
evaluate performance.
4. Tuning the PID Parameters: Adjust the PID parameters (Kp, Ki, Kd) to
minimize overshoot and settling time.

Scientific Programming Tools:

 Languages: Python, MATLAB, Simulink


 Libraries: control (Python), scipy.signal (Python), Simulink (MATLAB)

Signal Processing: Filtering and Spectral Analysis


Problem: Design of a Digital Filter for Signal Processing

Application: Digital signal processing (DSP) involves filtering signals to remove


noise or unwanted frequencies. A low-pass filter can be designed to allow only
signals with frequencies lower than a cutoff frequency to pass through, while
higher frequencies are attenuated.

Steps Involved:
44
1. Filter Design: Design a digital low-pass filter using the Butterworth or
Chebyshev method.
2. Frequency Response Analysis: Analyze the frequency response of the filter
to ensure it meets the desired specifications (e.g., cutoff frequency,
passband ripple).
3. Simulation: Apply the filter to a noisy signal and check the output.

Scientific Programming Tools:

 Languages: Python, MATLAB


 Libraries: scipy.signal (Python), Signal Processing Toolbox (MATLAB)

Power Systems: Load Flow Analysis


Problem: Power Flow in an Electrical Grid

Application: In electrical power systems, load flow analysis (also known as power
flow analysis) is used to determine the voltage, current, power, and impedance at
different points in the network. This helps in understanding how power is
distributed and how the system behaves under different load conditions.

Steps Involved:

1. Power Flow Model: Represent the electrical network as a system of


equations based on Kirchhoff’s laws.
2. Solve Power Flow Equations: Use iterative methods (like Gauss-Seidel or
Newton-Raphson) to solve the system.
3. Analysis: Analyze the voltage levels, power losses, and stability of the grid.

Scientific Programming Tools:

 Languages: Python, MATLAB


 Libraries: numpy, scipy (Python), Power System Toolbox (MATLAB)

45
PROGRAM 10 : Data Manipulation and Analysis using Pandas and MATLAB

Data Manipulation and Analysis using Pandas

import pandas as pd

# --- 1. Create a DataFrame from a Dictionary ---

data = {

'Name': ['Alice', 'Bob', 'Charlie', 'David'],

'Age': [25, 30, 35, 40],

'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']

# Creating a DataFrame

df = pd.DataFrame(data)

# Display the DataFrame

print("Initial DataFrame:")

print(df)

print("\n")

# --- 2. Reading Data from a CSV File (Simulated by creating a DataFrame) ---

# Assuming you have a CSV file (Here we're simulating it by creating a


DataFrame directly)

# --- 3. Selecting and Indexing Data ---

# Accessing a specific column

print("Accessing the 'Name' column:")

print(df['Name'])

print("\n")

46
# Accessing multiple columns

print("Accessing 'Name' and 'Age' columns:")

print(df[['Name', 'Age']])

print("\n")

# Accessing a specific row by index

print("Accessing the row at index 2 (Charlie):")

print(df.loc[2])

print("\n")

# Accessing the second row (position-based)

print("Accessing the second row (position 1):")

print(df.iloc[1])

print("\n")

# --- 4. Data Cleaning ---

# Create a DataFrame with missing data

data_with_nan = {

'Name': ['Alice', 'Bob', 'Charlie', None],

'Age': [25, None, 35, 40],

'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']

df_nan = pd.DataFrame(data_with_nan)

# Fill missing values

df_nan['Name'].fillna('Unknown', inplace=True)

df_nan['Age'].fillna(0, inplace=True)

47
print("DataFrame after handling missing values:")

print(df_nan)

print("\n")

# --- 5. Dropping Duplicates ---

data_duplicates = {

'Name': ['Alice', 'Bob', 'Charlie', 'Alice'],

'Age': [25, 30, 35, 25],

'City': ['New York', 'Los Angeles', 'Chicago', 'New York']

df_duplicates = pd.DataFrame(data_duplicates)

# Drop duplicate rows

df_unique = df_duplicates.drop_duplicates()

print("DataFrame after dropping duplicates:")

print(df_unique)

print("\n")

# --- 6. Data Transformation ---

# Adding a new column based on existing data

df['Age in 5 Years'] = df['Age'] + 5

print("DataFrame with a new column 'Age in 5 Years':")

print(df)

print("\n")

# Apply a function to the 'Age' column to increment it

df['Age'] = df['Age'].apply(lambda x: x + 1)

48
print("DataFrame after applying a function to increment the 'Age' column:")

print(df)

print("\n")

# --- 7. Grouping Data ---

# Group by 'City' and calculate the average age

grouped_df = df.groupby('City')['Age'].mean()

print("Average Age by City:")

print(grouped_df)

print("\n")

# --- 8. Merging DataFrames ---

# Create another DataFrame for merging

data2 = {

'Name': ['Alice', 'Bob', 'Charlie', 'David'],

'Salary': [50000, 60000, 70000, 80000]

df2 = pd.DataFrame(data2)

# Merge the two DataFrames on the 'Name' column

merged_df = pd.merge(df, df2, on='Name')

print("Merged DataFrame:")

print(merged_df)

print("\n")

# --- 9. Saving DataFrame to a CSV File ---

# Save the DataFrame to a CSV file (uncomment to run this part)

49
# df.to_csv('output.csv', index=False)

OUTPUT:
Initial DataFrame:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
3 David 40 Houston

Accessing the 'Name' column:


0 Alice
1 Bob
2 Charlie
3 David
Name: Name, dtype: object

Accessing 'Name' and 'Age' columns:


Name Age
0 Alice 25
1 Bob 30
2 Charlie 35
3 David 40

Accessing the row at index 2 (Charlie):


Name Charlie
Age 35
City Chicago
Name: 2, dtype: object
Accessing the second row (position 1):
Name Bob
Age 30
City Los Angeles
Name: 1, dtype: object

50
DataFrame after handling missing values:
Name Age City
0 Alice 25 New York
1 Bob 0 Los Angeles
2 Charlie 35 Chicago
3 Unknown 40 Houston

DataFrame after dropping duplicates:


Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago

DataFrame with a new column 'Age in 5 Years':


Name Age City Age in 5 Years
0 Alice 25 New York 30
1 Bob 30 Los Angeles 35
2 Charlie 35 Chicago 40
3 David 40 Houston 45

DataFrame after applying a function to increment the 'Age' column:


Name Age City Age in 5 Years
0 Alice 26 New York 30
1 Bob 31 Los Angeles 35
2 Charlie 36 Chicago 40
3 David 41 Houston 45

Average Age by City:


City
Chicago 36.0
Houston 41.0
Los Angeles 31.0

51
New York 26.0
Name: Age, dtype: float64

Merged DataFrame:
Name Age City Age in 5 Years Salary
0 Alice 26 New York 30 50000
1 Bob 31 Los Angeles 35 60000
2 Charlie 36 Chicago 40 70000
3 David 41 Houston 45 80000

Data Manipulation and Analysis using MATLAB


% 1. Creating Arrays and Data Structures

% Creating a numeric array


A = [1, 2, 3, 4, 5]; % Row vector
B = [1; 2; 3; 4; 5]; % Column vector

% Creating a matrix (2D array)


C = [1, 2, 3; 4, 5, 6; 7, 8, 9];

% Display the matrices


disp('Row vector A:');
disp(A);

disp('Column vector B:');


disp(B);

disp('Matrix C:');
disp(C);

% 2. Creating a Table
Names = {'Alice', 'Bob', 'Charlie', 'David'};
Ages = [25, 30, 35, 40];
Cities = {'New York', 'Los Angeles', 'Chicago', 'Houston'};

52
T = table(Names', Ages', Cities');
disp('Table of people data:');
disp(T);

% 3. Accessing Data from Arrays and Tables

% Accessing individual elements in arrays


first_value = A(1); % First element of A
second_row_first_column = C(2, 1); % Element in second row, first column of
C

disp('First value of A:');


disp(first_value);

disp('Element at position (2,1) in C:');


disp(second_row_first_column);

% Accessing table columns by name


names_col = T.Names;
ages_col = T.Ages;

% Accessing specific row and column in the table


first_person = T(1, :); % First row of the table

disp('Names column from the table:');


disp(names_col);

disp('First person from the table:');


disp(first_person);

% 4. Handling Missing Data

% Creating a table with missing data

53
Age = [25, NaN, 35, 40];
City = {'New York', 'Los Angeles', 'Chicago', 'Houston'};

T_with_missing = table(Age', City');


disp('Table with missing data:');
disp(T_with_missing);

% Replace NaN with a specific value (e.g., 0)


T_with_missing.Age(isnan(T_with_missing.Age)) = 0;

disp('Table after replacing NaN with 0:');


disp(T_with_missing);

% 5. Creating a New Column in the Table

% Adding a new column 'Age_in_5_years' to the table


T_with_missing.Age_in_5_years = T_with_missing.Age + 5;

disp('Table with new column "Age_in_5_years":');


disp(T_with_missing);

% 6. Basic Statistical Operations

% Calculating basic statistics for the Age column


mean_age = mean(T_with_missing.Age);
std_age = std(T_with_missing.Age);
min_age = min(T_with_missing.Age);
max_age = max(T_with_missing.Age);

disp(['Mean age: ', num2str(mean_age)]);


disp(['Standard deviation of age: ', num2str(std_age)]);
disp(['Minimum age: ', num2str(min_age)]);
disp(['Maximum age: ', num2str(max_age)]);

54
% 7. Saving Data to a CSV File
writetable(T_with_missing, 'people_data.csv');
disp('Data saved to people_data.csv');

OUTPUT: Row vector A:


1 2 3 4 5

Column vector B:
1
2
3
4
5

Matrix C:
1 2 3
4 5 6
7 8 9

Table of people data:


Names Ages Cities
_______ _____ _________
'Alice' 25 'New York'
'Bob' 30 'Los Angeles'
'Charlie' 35 'Chicago'
'David' 40 'Houston'

First value of A:
1

Element at position (2,1) in C:


4

Names column from the table:

55
'Alice' 'Bob' 'Charlie' 'David'

First person from the table:


Names: 'Alice' Ages: 25 Cities: 'New York'

Table with missing data:


Age City
___ ___________
25 'New York'
NaN 'Los Angeles'
35 'Chicago'
40 'Houston'

Table after replacing NaN with 0:


Age City
___ ___________
25 'New York'
0 'Los Angeles'
35 'Chicago'
40 'Houston'
Table with new column "Age_in_5_years":
Age City Age_in_5_years
___ ___________ _______________
25 'New York' 30
0 'Los Angeles' 5
35 'Chicago' 40
40 'Houston' 45
Mean age: 25
Standard deviation of age: 17.677
Minimum age: 0
Maximum age: 40

Data saved to people_data.csv

56
PROGRAM 11 : Creating Various Plots(Line,Scatter,Bar,Histogram)

import matplotlib.pyplot as plt


import numpy as np

# Data for plotting


x = np.linspace(0, 10, 100) # 100 points between 0 and 10
y = np.sin(x) # Sine of x
y2 = np.cos(x) # Cosine of x
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 30]

# 1. Line Plot
plt.figure(figsize=(10, 6)) # Set the figure size
plt.plot(x, y, label='sin(x)', color='blue') # Line plot for sin(x)
plt.plot(x, y2, label='cos(x)', color='red') # Line plot for cos(x)
plt.title('Line Plot Example')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.legend() # Show legend
plt.grid(True) # Display grid
plt.show()

57
# 2. Scatter Plot
plt.figure(figsize=(10, 6))
plt.scatter(x, y, label='sin(x)', color='green') # Scatter plot for sin(x)
plt.scatter(x, y2, label='cos(x)', color='purple') # Scatter plot for cos(x)
plt.title('Scatter Plot Example')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.legend()
plt.show()

# 3. Bar Plot
plt.figure(figsize=(10, 6))
plt.bar(categories, values, color='orange') # Bar plot
plt.title('Bar Plot Example')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()

58
# 4. Histogram
data = np.random.randn(1000) # Generate 1000 random numbers from
normal distribution
plt.figure(figsize=(10, 6))
plt.hist(data, bins=30, color='cyan', edgecolor='black') # Histogram
plt.title('Histogram Example')
plt.xlabel('Data Values')
plt.ylabel('Frequency')
plt.show()

59
60
PROGRAM 12 : Customizing and Interpreting Plots for Engineering Data

import matplotlib.pyplot as plt


import numpy as np

# Example 1: Temperature vs. Time (Line Plot)


time = np.linspace(0, 24, 100) # Time from 0 to 24 hours
temperature = 20 + 5 * np.sin(2 * np.pi * time / 24) # Simulated temperature
variation

plt.figure(figsize=(10, 6))
plt.plot(time, temperature, label='Temperature', color='blue', linestyle='-',
marker='o', markersize=5)
plt.title('Temperature Variation Over 24 Hours', fontsize=14)
plt.xlabel('Time (hours)', fontsize=12)
plt.ylabel('Temperature (°C)', fontsize=12)
plt.grid(True)
plt.legend(loc='upper right')
plt.tight_layout()
plt.show()

# Example 2: Signal Plot (Sine Wave)


frequency = 50 # Frequency of the signal in Hz
sampling_rate = 1000 # Samples per second
t = np.linspace(0, 1, sampling_rate) # Time vector for 1 second
signal = np.sin(2 * np.pi * frequency * t) # Sine wave signal

plt.figure(figsize=(10, 6))
plt.plot(t, signal, label='Signal', color='red', linestyle='-', linewidth=1.5)
plt.title('Sine Wave Signal (50 Hz)', fontsize=14)
plt.xlabel('Time (seconds)', fontsize=12)
plt.ylabel('Amplitude', fontsize=12)
plt.grid(True, which='both', linestyle='--', color='gray')
plt.legend(loc='upper right')

61
plt.tight_layout()
plt.show()

# Example 3: Histogram of Voltage Measurements


voltage_measurements = np.random.normal(loc=230, scale=10, size=1000) #
Simulated voltage data around 230V

plt.figure(figsize=(10, 6))
plt.hist(voltage_measurements, bins=30, color='green', edgecolor='black',
alpha=0.7)
plt.title('Histogram of Voltage Measurements', fontsize=14)
plt.xlabel('Voltage (V)', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
plt.grid(True, linestyle='--')
plt.tight_layout()
plt.show()

# Example 4: Electrical Power vs. Resistance (Ohm’s Law Plot)


voltage = 10 # Voltage in volts
resistance = np.linspace(1, 100, 100) # Resistance from 1 ohm to 100 ohms
current = voltage / resistance # Current using Ohm's Law (I = V/R)
power = voltage * current # Power using P = VI

plt.figure(figsize=(10, 6))
plt.plot(resistance, power, label='Power vs. Resistance', color='purple',
linestyle='-', marker='x')
plt.title('Power vs. Resistance (Ohm’s Law)', fontsize=14)
plt.xlabel('Resistance (Ohms)', fontsize=12)
plt.ylabel('Power (Watts)', fontsize=12)
plt.grid(True, linestyle='-.', color='orange')
plt.legend(loc='upper right')
plt.tight_layout()
plt.show()

62
63
64
PROGRAM 13 : Implementing Basic Machine Learning Algorithms in Python

Implementing basic machine learning algorithms in Python is essential to


understand how machine learning models work. Here, we'll implement some of
the most common algorithms: Linear Regression, Logistic Regression, K-Nearest
Neighbors (KNN), and Decision Trees. We will also demonstrate how to evaluate
these models using a sample dataset. To implement these algorithms, we will use
libraries such as scikit-learn, numpy, and matplotlib.

1. Linear Regression Example (Supervised Learning)

Linear regression is a fundamental machine learning algorithm used for predicting


a continuous value based on the input features.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

# Generate some synthetic data (y = 2x + 1)


X = np.random.rand(100, 1) * 10 # 100 random values for X (from 0 to 10)
y = 2 * X + 1 + np.random.randn(100, 1) # y = 2x + 1 with some noise

# Split data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)

# Initialize Linear Regression model


model = LinearRegression()

# Train the model


model.fit(X_train, y_train)

# Make predictions
y_pred = model.predict(X_test)

65
# Evaluate the model
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")

# Plotting the results


plt.scatter(X_test, y_test, color='blue', label='Actual data')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='Predicted line')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Linear Regression')
plt.legend()
plt.show()

Mean Squared Error: 0.6742030217027715

Logistic Regression Example (Supervised Learning)

Logistic regression is used for binary classification tasks, where the goal is to
predict the probability of a class (e.g., 0 or 1).

from sklearn.datasets import load_iris


from sklearn.linear_model import LogisticRegression
66
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix

# Load the Iris dataset


iris = load_iris()
X = iris.data
y = iris.target

# We will use only two classes (binary classification for simplicity)


X = X[y != 2]
y = y[y != 2]

# Split data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)

# Initialize Logistic Regression model


log_reg = LogisticRegression()

# Train the model


log_reg.fit(X_train, y_train)

# Make predictions
y_pred = log_reg.predict(X_test)

# Evaluate the model


accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
print(f"Confusion Matrix:\n{confusion_matrix(y_test, y_pred)}")

Accuracy: 1.0
Confusion Matrix:
[[17 0]
[ 0 13]]

67
K-Nearest Neighbors (KNN) Example (Supervised Learning)

K-Nearest Neighbors (KNN) is a simple and intuitive algorithm used for both
classification and regression tasks. In this example, we'll use it for classification.

from sklearn.neighbors import KNeighborsClassifier


from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Load the Iris dataset


iris = load_iris()
X = iris.data
y = iris.target

# Split data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)

# Initialize KNN model with 3 neighbors


knn = KNeighborsClassifier(n_neighbors=3)

# Train the model


knn.fit(X_train, y_train)

# Make predictions
y_pred = knn.predict(X_test)

# Evaluate the model


accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")

Accuracy: 1.0

68
Decision Tree Classifier Example (Supervised Learning)

Decision Trees are used for classification and regression tasks. Here, we'll
implement it for classification.

from sklearn.tree import DecisionTreeClassifier


from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Load the Iris dataset


iris = load_iris()
X = iris.data
y = iris.target

# Split data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)

# Initialize Decision Tree model


dt = DecisionTreeClassifier()

# Train the model


dt.fit(X_train, y_train)

# Make predictions
y_pred = dt.predict(X_test)

# Evaluate the model


accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")

Accuracy: 1.0

69
PROGRAM 14 : Exploring IoT and Big Data Tools
Exploring IoT (Internet of Things) and Big Data Tools can provide insight into
how these technologies work and how they are applied to real-world scenarios.
Both IoT and Big Data are critical components of modern computing, enabling
industries to collect, process, and analyze vast amounts of data in real-time for
better decision-making and automation.
Common IoT Applications:

 Smart Homes: Devices like smart thermostats (e.g., Nest), smart lights, and
voice assistants (e.g., Amazon Alexa, Google Assistant).
 Wearables: Devices like Fitbit or smartwatches that collect health and
fitness data.
 Healthcare: Remote monitoring systems, wearables for health tracking, and
hospital equipment.
 Agriculture: Smart farming using IoT-enabled sensors for soil moisture,
temperature, and weather conditions.
 Industry 4.0: Industrial IoT (IIoT) sensors and systems that monitor
production lines, machinery, and energy consumption.

IoT Tools

Several platforms and tools are available to work with IoT systems. These tools
facilitate the deployment, management, and integration of IoT devices.

IoT Platforms and Development Tools

 Arduino: An open-source electronics platform used for building IoT devices.


It consists of a microcontroller board and software development
environment.
 Raspberry Pi: A small single-board computer that can be used for building
IoT projects.
 ThingSpeak: An IoT platform for connecting IoT devices, collecting data, and
visualizing it in real-time.
 AWS IoT: Amazon Web Services offers a suite of tools (including AWS IoT
Core) to securely connect IoT devices to the cloud and perform data
analytics.
 Google Cloud IoT: A fully managed suite of tools for building IoT
applications using Google's cloud infrastructure.
 Microsoft Azure IoT Hub: A platform for managing and securing IoT devices,
ingesting data, and running analytics.

70
IoT Protocols

 MQTT (Message Queuing Telemetry Transport): A lightweight messaging


protocol designed for low-bandwidth, high-latency networks. MQTT is often
used for IoT communications.
 CoAP (Constrained Application Protocol): Another lightweight protocol
designed for constrained devices and low-power, low-bandwidth networks.
 HTTP/HTTPS: Common protocols for IoT communication but less efficient in
terms of bandwidth compared to MQTT and CoAP.
 LoRaWAN (Long Range Wide Area Network): A wireless protocol for long-
range, low-power communications for IoT devices.

Big Data Tools :


Big Data refers to datasets that are too large or complex to be handled by
traditional data processing systems. Big Data typically encompasses data that is
high-volume, high-velocity, and high-variety. It can include everything from
social media posts, sensor data from IoT devices, financial transactions, and
medical records, to data generated by online activities, etc.
Big Data Storage Tools

 Hadoop: An open-source framework that stores and processes large


datasets in a distributed computing environment. It includes components
like HDFS (Hadoop Distributed File System) and MapReduce (for distributed
processing).
 Apache HBase: A distributed, column-oriented NoSQL database that runs
on top of HDFS and is used for real-time read/write access to large datasets.
 Amazon S3 (Simple Storage Service): A scalable storage service for storing
any amount of data, often used for Big Data storage.
 Google Cloud Storage: Similar to Amazon S3, Google Cloud Storage offers
scalable storage services for Big Data.

Big Data Processing Frameworks

 Apache Spark: A powerful open-source engine for large-scale data


processing. Spark can perform both batch and real-time processing and is
much faster than traditional MapReduce-based systems.
 Apache Flink: A framework for distributed stream processing that allows
you to process data in real-time.
 Apache Kafka: A distributed event streaming platform used for building
real-time data pipelines and streaming applications.

Big Data Analytics Tools

71
 Apache Hive: A data warehouse system built on top of Hadoop for querying
and managing large datasets.
 Apache Pig: A platform for analyzing large datasets that provide a high-level
scripting language.
 PrestoDB: A distributed SQL query engine designed for running interactive
analytic queries on large datasets.
 Tableau: A powerful data visualization tool that helps in creating interactive
and shareable dashboards to analyze Big Data.
 Power BI: Microsoft’s business analytics service that allows for data
visualization and sharing insights from Big Data.

Data Processing Languages

 SQL: Traditional query language for managing structured data.


 Python: Popular for Big Data analytics due to libraries like Pandas, Dask,
NumPy, and PySpark.
 R: A language for statistical computing and graphics, widely used for data
analysis.
 Scala: Often used in conjunction with Spark for processing large datasets.

IoT + Big Data Integration

The integration of IoT and Big Data plays a significant role in industries like
manufacturing, healthcare, and smart cities, where IoT devices collect massive
amounts of data that need to be processed and analyzed for real-time decision-
making. Here are some ways these technologies work together:

 Data Collection via IoT Devices: Sensors and IoT devices collect real-time
data (e.g., from manufacturing machines, smart home devices, or wearable
health devices).
 Data Streaming and Processing: The data is sent to cloud platforms (e.g.,
AWS IoT, Google Cloud IoT) or to Big Data platforms like Apache Kafka or
Apache Flink for real-time processing.
 Big Data Storage: The processed data is stored in Big Data platforms such as
Hadoop, HBase, or NoSQL databases like MongoDB.
 Analytics and Insights: Advanced analytics using tools like Apache Spark,
Presto, or machine learning models to gain insights from the data. These
insights are then used for decision-making, predictive maintenance, or
anomaly detection.

72
PROGRAM 15 : Working on Individual/Group Projects
PROGRAM 16 : Preparing Project Reports and Presentations
PROGRAM 17 : Final Projection Presentation
Working on individual or group projects using scientific programming can be
both rewarding and challenging. It provides an opportunity to apply
mathematical and computational techniques to solve real-world problems.
These projects often involve using programming languages such as Python,
MATLAB, R, or other domain-specific languages that facilitate mathematical
modeling, data analysis, and simulation. Below are some general steps and
considerations for working on these types of projects.
1. Defining the Project

Whether you're working alone or in a group, the first step is defining the project's
scope and objectives clearly. This is where you decide the problem you are trying
to solve, which data or systems you need to work with, and what tools and
methods you will use.

Key steps for defining the project:

 Identify the Problem: What specific problem do you want to solve? Is it


related to physics, engineering, machine learning, or data analysis? For
example, in electronics, you might simulate an electrical circuit, while in
data science, you might analyze trends in a dataset.
 Set Clear Goals: What do you aim to achieve? For example, is it a
simulation, optimization, or model-building task? Define the key
deliverables and milestones for the project.
 Choose Tools and Libraries: Depending on the problem, you might need
specific scientific libraries or tools. For example, you might use:
o Python: Libraries like NumPy, SciPy, Matplotlib, Pandas, TensorFlow,
PyTorch, etc.
o MATLAB: Built-in functions and toolboxes like Simulink, Optimization
Toolbox, etc.
o R: Libraries like ggplot2, dplyr, and caret for statistical analysis and
visualization.
 Team Organization (for Group Projects): If you're working in a group,
decide on roles and responsibilities. For example, one person might be in
charge of coding, another for data collection, and another for visualization
and reporting.

2. Data Collection & Preparation

For many scientific programming projects, the first step is collecting and preparing
73
data. Data might come from sensors, databases, simulations, or online resources.

Steps to follow:

 Data Collection: Ensure the data you're collecting is reliable and relevant to
your problem. For instance, if you're working on environmental modeling,
you might collect data from sensors or databases related to temperature,
humidity, air quality, etc.
 Data Cleaning: Raw data often needs preprocessing. This includes removing
outliers, filling missing values, normalizing, and transforming the data into a
usable format.
 Data Storage: Organize your data properly in files (CSV, JSON, etc.) or
databases (SQL, NoSQL).

3. Algorithm Development

Once you have your data, the next step is to develop algorithms to analyze,
process, or model the data. This could involve implementing numerical methods,
optimization techniques, machine learning models, etc.

Examples of algorithms:

 Numerical Methods:
o Solving linear systems of equations (using Gaussian elimination, LU
decomposition).
o Optimization techniques (gradient descent, Newton-Raphson
method).
o Interpolation and integration (e.g., Newton's interpolating polynomial
or Simpson's rule for numerical integration).
 Machine Learning:
o Supervised Learning: Implement regression (linear regression,
decision trees) or classification (SVM, KNN, neural networks).
o Unsupervised Learning: Clustering algorithms like k-means,
hierarchical clustering, or dimensionality reduction techniques like
PCA.
 Simulation:
o For example, simulating a physical process like projectile motion or
circuit behavior (using methods such as Monte Carlo simulations or
finite element analysis).

4. Visualization

Visualization helps you interpret the results of your calculations. Scientific

74
programming projects often require you to plot graphs, charts, or 3D
visualizations.

Libraries for visualization:

 Python:
o Matplotlib: For creating 2D graphs and plots.
o Seaborn: Built on top of Matplotlib for advanced statistical plotting.
o Plotly: For interactive visualizations.
o Mayavi/Plotly: For 3D visualizations.
 MATLAB:
o Built-in functions such as plot, surf, mesh, etc., allow for 2D and 3D
plotting.

5. Testing and Validation

Once the algorithm is implemented, you must test and validate it to ensure it
works as expected. This involves:

 Unit Testing: Testing individual parts of the code to check their correctness.
 Integration Testing: Verifying if different parts of the system work well
together.
 Validation: Comparing your results with real-world data or known
benchmarks.

6. Documentation and Reporting

For both individual and group projects, proper documentation is crucial. This
includes:

 Code Documentation: Use comments and docstrings to explain the


functionality of your code.
 Reports: If this is a larger project, you might be asked to submit a report
that explains:
o Problem statement
o Methods used
o Results and interpretation
o Conclusions and recommendations

LaTeX or Markdown can be useful for writing professional reports, and


libraries like Jupyter Notebooks (Python) are great for combining code, text,
and visualizations in one place.

75
7. Collaboration (for Group Projects)

If you're working in a group, it is essential to use collaboration tools and version


control systems.

Tools for Collaboration:

 Git/GitHub: Version control for tracking changes and collaboration. Git


allows multiple people to work on the same project simultaneously.
 Slack/Teams: Communication platforms for quick collaboration.
 Trello/Asana: Project management tools to track tasks and progress.

Whether working on an individual or group project, scientific programming allows


you to apply mathematical models and data analysis techniques to solve problems
in diverse fields such as physics, engineering, and data science. The key to success
in such projects is:

1. Clearly defining the problem.


2. Choosing the right tools and libraries.
3. Ensuring proper testing and validation.
4. Collaborating efficiently if working in a team.
5. Documenting and reporting your results.

These steps will help ensure that your scientific programming project is well-
executed and produces meaningful, interpretable results.

76

You might also like