You are on page 1of 14

UNIT-V

Matlab/Python Lib: Introduction to Matlab/Python, Arrays and array operations, Functions and Files,
Study of neural network toolbox and fuzzy logic toolbox, Simple implementation of Artificial Neural
Network and Fuzzy Logic.

MATLAB:
MATLAB is a coding language and a licensed mathematical computing ecosystem. It's great for
manipulating matrices, visualizing data, executing algorithms, and creating interactive user interfaces.
MATLAB Uses and Features:
1. Putting a simulation to the test.
2. Can be used for image processing.
3. MATLAB is both a language of programming and a programming interface.
Python:
Python is a popular programming language. It was created in 1991 by Guido Van Rossum and is based
on the Python software platform. Python is a programming language that allows us to function fast and
productively on systems. Python provides a variety of programming methodologies, including
algorithmic programming, object-oriented programming, as well as functional programming. It is a
user-friendly interface. It is easy to understand and execute. It is open-source.
Python Uses and Features:
1. It is simple to learn (clean, clear syntax).
2. High portability
3. Blocks are separated by white space.
Python MATLAB
Data types and numeric arrays, A Languages that are oriented to math and
general-purpose, high-performance matrices. MATLAB is a high-level
Definition
scripting language. programming language for scientific
computation.
Python is a coding language that we may Matrix operations, functions and data
Usage use to create websites. plotting, and user interface design are all
possible with MATLAB.
A large number of support libraries are MATLAB makes it possible to test
Benefits available. algorithms without having to compile
them first.
Community engagement and open- Installing, compiling, verifying, and using
Performance
source software. add-ons for the developers improves

Page 1 of 14
performance.
Linear algebra, visuals, and analytics Since the 1970s, there has been a
Academics with high performance. Call libraries rudimentary version of MATLAB on the
that are optimized for them. market.
Python was created in 1991 by the There are no generic programming
Library
Python Software Foundation. capabilities in the standard library.
Real-time It is made up of a large standard library. There is no individualized real-time
Support assistance.
Embedded Email and phone assistance that is MATLAB generates portable, under
Code tailored to our needs
Generation

__________________________________________________________________________________

Arrays and array operations in MATLAB

An array is a collection of elements with the same data type. A vector is a one-dimensional array, and
a matrix is a two-dimensional array. We can create arrays in multiple ways in MATLAB.
By using space in between elements:

• This command creates an array variable 'A' having one row and four columns. The output will
be displayed in the command window as:

By using comma in between elements:

• This command will create an array variable 'a' having one row and four columns and the output
will be displayed in the command window as:

• We can combine both approaches into one, but this is not a good practice.

Page 2 of 14
• The array having a single row is known as a row vector. Or we can say a single-dimensional
array is a vector.
• A two-dimensional array is called a matrix. It means a matrix has multiple rows and columns.
So, while creating a matrix with multiple rows, we have to separate the rows with semicolons.

• Be careful while creating a matrix, each row should have the same number of columns, and
each row should be separated with a semicolon. Otherwise, it will show error and won't create
the matrix.
• We can create a matrix by using the in-built function, such as ones, zeros, or rand.

MATLAB support two categories of operations between arrays, known as array


operations and matrix operations.
Array operations are operations implemented between arrays. That is, the operation is implemented on
corresponding elements in the two arrays. For example,

Array operations may also appear between an array and a scalar. If the operation is performed between
an array and a scalar, the value of the scalar is applied to every element of the array. For example,

Page 3 of 14
Examples of Matrix and Array Operations:
• We can process all of the values in a matrix using a single arithmetic operator.

• Note: it will not change the original variable 'a'. The above output assigned to the default
variable 'ans.'
• We can process the whole matrix using a single function, as well.

• Use single quote (') after the variable, to transpose the matrix.

Concatenation of Arrays in MATLAB:


MATLAB is also support join the two arrays. The pair of square brackets [ ] used in the declaration of
the array is itself a concatenation operator. We can concatenate the arrays in two ways:
i) Horizontal Concatenation of Arrays in MATLAB:
• Rule: all arrays should have the same number of rows.
• Syntax: enclose all arrays in square bracket separated by commas, [a, b, c].

Page 4 of 14
ii) Vertical Concatenation of Arrays in MATLAB:
• Rule: all arrays should have the same number of columns.
• Syntax: enclose all arrays in square bracket separated by semi-colons, [a;b;c].

Array Indexing in MATLAB:

Page 5 of 14
All the elements in the array are indexed as per row and column. Any particular element can be
accessed using indexing in MATLAB.
Vector Creation Using Colon Operator in MATLAB:
By using the colon operator, we can create an equally spaced vector of values. We can assign step
value that can affect the next value at a fixed interval.
Syntax: start: step: end.

__________________________________________________________________________________

Arrays and arrays operations in Phyton:


An array is defined as a collection of items that are stored at contiguous memory locations. Array is
created in Python by importing array module to the python program. Then the array is declared as
shown below.
from array import *
arrayName = array(typecode, [Initializers])
Typecode are the codes that are used to define the type of value the array will hold. Example b,B,c,d
etc.
Basic Operations:

Following are the basic operations supported by an array.


• Traverse − print all the array elements one by one.
• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the value.
• Update − Updates an element at the given index.

Accessing Array Element: We can access each element of an array using the index of the element.
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])

Page 6 of 14
When we compile and execute the above program, it produces the following result.
Output: 10
30

Insertion Operation: Insert operation is to insert one or more data elements into an array. Based on
the requirement, a new element can be added at the beginning, end, or any given index of array. Here,
we add a data element at the middle of the array using the python in-built insert() method.
from array import *
array1 = array('i', [10,20,30,40,50])
array1.insert(1,60)
for x in array1:
print(x)
When we compile and execute the above program, it produces the following result.
Output
10
60
20
30
40
50

Deletion Operation: Deletion refers to removing an existing element from the array and re-organizing
all elements of an array. Here, we remove a data element at the middle of the array using the python
in-built remove() method.
from array import *
array1 = array('i', [10,20,30,40,50])
array1.remove(40)
for x in array1:
print(x)
When we compile and execute the above program, it produces the following result
Output
10
20
30
50
Search Operation: You can perform a search for an array element based on its value or its index.
Here, we search a data element using the python in-built index() method.
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1.index(40))
When we compile and execute the above program, it produces the following result.

Page 7 of 14
Output: 3
Update Operation: Update operation refers to updating an existing element from the array at a given
index. Here, we simply reassign a new value to the desired index we want to update.
from array import *
array1 = array('i', [10,20,30,40,50])
array1[2] = 80
for x in array1:
print(x)
When we compile and execute the above program, it produces the following result which shows the
new value at the index position 2.
Output
10
20
80
40
50
__________________________________________________________________________________
Functions in Python/MatLab:
A function is a block of code that performs a specific task. There are two types of functions:

• Standard library functions - These are built-in functions in Python that are available to use.
• User-defined functions - We can create our own functions based on our requirements.
Syntax:
def function_name(arguments):
return
Here,
• def- keyword used to declare a function
• function_name - any name given to the function
• arguments - any value passed to function
• return (optional) - returns value from a function
Calling a Function in Python:

In the above example, we have declared a function named greet().


def greet():
print('Hello World!')
Now, to use this function, we need to call it.Here's how we can call the greet() function in Python.

# call the function


greet()

Page 8 of 14
Python Function Arguments: A function can also have arguments. An argument is a value that is
accepted by a function. For example,

# function with two arguments


def add_numbers(num1, num2):
sum = num1 + num2
print('Sum: ',sum)
If we create a function with arguments, we need to pass the corresponding values while calling them.
For example,

# function call with two values


add_numbers(5, 4)
Return: A Python function may or may not return a value. If we want our function to return some
value to a function call, we use the return statement. For example,

def add_numbers():
...
return sum
Python Library Functions: In Python, standard library functions are the built-in functions that can be
used directly in our program. For example,

• print() - prints the string inside the quotation marks


• sqrt() - returns the square root of a number
• pow() - returns the power of a number
______________________________________________________________________
Files in Python:
A file is a container in computer storage devices used for storing data. When we want to read from or
write to a file, we need to open it first. When we are done, it needs to be closed. In Python, a file
operation takes place in the following order:
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening Files in Python: In Python, we use the open() method to open files. suppose we have a file
named test.txt with the following content. We try to open data from this file using the open() function.

# open file in current directory


file1 = open("test.txt") or file1=open(“test.txt”,”r”)

Page 9 of 14
Here, we have created a file object named file1. This object can be used to work with files and
directories. By default, the files are open in read mode (cannot be modified).
Different Modes to Open a File in Python

Mode Description

r Open a file for reading. (default)


Open a file for writing. Creates a new file if it does not exist or truncates the file
w
if it exists.
x Open a file for exclusive creation. If the file already exists, the operation fails.
Open a file for appending at the end of the file without truncating it. Creates a
a
new file if it does not exist.
t Open in text mode. (default)
b Open in binary mode.
+ Open a file for updating (reading and writing)

Reading Files in Python: After we open a file, we use the read() method to read its contents.

# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
Output:
This is a test file.
Hello from the test file.
Closing Files in Python: When we are done with performing operations on the file, we need to
properly close the file. It is done using the close() method in Python.

# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
# close the file
file1.close()

Page 10 of 14
Output:
This is a test file.
Hello from the test file.
__________________________________________________________________________________
Explain Study of neural network toolbox and fuzzy logic toolbox in MATLAB
The Neural Network Toolbox and Fuzzy Logic Toolbox are two powerful toolboxes in MATLAB that
provide complete functionalities for working with neural networks and fuzzy logic systems.
Neural Network Toolbox: The Neural Network Toolbox in MATLAB is designed for creating,
training, visualizing, and simulating artificial neural networks (ANNs). Here are some key features:
• Neural Network Architectures: The toolbox supports various types of neural networks,
including feedforward networks, recurrent networks, self-organizing maps, and dynamic
networks. Users can easily define network architectures, number of layers and activation
functions.
• Training Algorithms: MATLAB's Neural Network Toolbox provides an extensive set of
training algorithms. These include backpropagation algorithms like gradient descent as well as
more advanced techniques like deep learning algorithms and unsupervised learning algorithms.
• Data Preprocessing: The toolbox offers number of data preprocessing techniques, such as
scaling, normalization, and PCA (Principal Component Analysis).
• Visualization and Analysis: MATLAB provides various functions for visualizing and
analyzing neural networks. Users can visualize network architectures, plot training curves,
analyze network performance metrics (e.g., accuracy, error).
• Deployment and Integration: The Neural Network Toolbox allows for easy deployment of
trained neural network models. Users can generate MATLAB code for deploying models in
real-world applications.

Page 11 of 14
Fuzzy Logic Toolbox: The Fuzzy Logic Toolbox in MATLAB provides tools for designing,
simulating, and implementing fuzzy logic systems. Here are some key features:
• Fuzzy Inference Systems: The toolbox enables the creation and evaluation of fuzzy inference
systems. Users can define fuzzy sets, linguistic variables, membership functions, and rules.
• Membership Function Design: MATLAB provides a range of functions for designing and
customizing membership functions. Users can define membership functions using standard
shapes (e.g., triangular, trapezoidal).
• Rule-Based Reasoning: The toolbox enables the construction and evaluation of fuzzy rule
bases. Users can define rules using linguistic variables and fuzzy logic operators, and perform
rule evaluation and aggregation using different methods.
• Defuzzification Methods: MATLAB provides multiple defuzzification methods for
converting fuzzy output into crisp values.
• Visualization and Analysis: The Fuzzy Logic Toolbox allows for visualizing and analyzing
fuzzy logic systems. Users can plot membership functions, visualize fuzzy rule bases to
understand the behavior of the system.
• Deployment and Integration: Fuzzy logic systems can be deployed and integrated into
MATLAB applications, Simulink models, or external systems using code generation.
__________________________________________________________________________________

Simple Implementation of Artificial Neural Network:


import numpy as np
Define sigmoid activation function
def sigmoid(x): return 1 / (1 + np.exp(-x))
Define the ANN class
class NeuralNetwork:
def init(self, input_size, hidden_size, output_size): # Initialize weights
self.weights1 = np.random.randn(input_size, hidden_size)
self.weights2 = np.random.randn(hidden_size, output_size)
def forward(self, X):
# Propagate inputs through the network
self.hidden_layer = sigmoid(np.dot(X, self.weights1))
self.output_layer = sigmoid(np.dot(self.hidden_layer, self.weights2))
return self.output_layer

Page 12 of 14
Create an instance of the NeuralNetwork class
input_size = 2
hidden_size = 3
output_size = 1
nn = NeuralNetwork(input_size, hidden_size, output_size)
Input data
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
Target output
y = np.array([[0], [1], [1], [0]])
Training loop
epochs = 10000
learning_rate = 0.1
for epoch in range(epochs):
# Forward pass
output = nn.forward(X)
# Backpropagation
error = y - output
output_delta = error * (output * (1 - output))
hidden_delta = output_delta.dot(nn.weights2.T) * (nn.hidden_layer * (1 -
nn.hidden_layer))
# Update weights
nn.weights2 += nn.hidden_layer.T.dot(output_delta) * learning_rate
nn.weights1 += X.T.dot(hidden_delta) * learning_rate
estimated the trained network
test_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
print(nn.forward(test_data))

Page 13 of 14
Simple Implementation of a Fuzzy Logic System:
import numpy as np
import skfuzzy as fuzz from skfuzzy
import control as ctrl
Create input and output fuzzy variables
temperature = ctrl.Antecedent(np.arange(0, 101, 1), 'temperature')
fan_speed = ctrl.Consequent(np.arange(0, 101, 1), 'fan_speed')
Define fuzzy membership functions
temperature['low'] = fuzz.trimf(temperature.universe, [0, 0, 50])
temperature['high'] = fuzz.trimf(temperature.universe, [0, 50, 100])
fan_speed['low'] = fuzz.trimf(fan_speed.universe, [0, 0, 50])
fan_speed['high'] = fuzz.trimf(fan_speed.universe, [0, 50, 100])
Define fuzzy rules
rule1 = ctrl.Rule(temperature['low'], fan_speed['low'])
rule2 = ctrl.Rule(temperature['high'], fan_speed['high'])
Create fuzzy control system
fan_ctrl = ctrl.ControlSystem([rule1, rule2])
fan_speed_ctrl = ctrl.ControlSystemSimulation(fan_ctrl)
Set input values
fan_speed_ctrl.input['temperature'] = 30

Page 14 of 14

You might also like