0% found this document useful (0 votes)
3 views62 pages

Sohan Matlab

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 62

BTCS 305-18 IT WORKSHOP FILE 2301695

IT WORSKHOP
PRACTICAL FILE
BTCS 305-18

Submitted To:- Submitted By:-


Mr Vinay Chopra Name: Sohan
B.Tech CSE B (3rd Sem)
Class Roll no: 847/23
Uni. Roll no: 2301695

1
BTCS 305-18 IT WORKSHOP FILE 2301695

INDEX
S.NO CONTENTS PAGE NO SIGNATURE
1 Introduction to MATLAB 3-5

2 Basics of MATLAB 6-12

3 Variables in MATLAB 13-14

4 Datatypes in MATLAB 15-18

5 Operators in MATLAB 19-22

6 Matrix in MATLAB 23-27

7 Arrays in MATLAB 28-29

8 Scripts and Functions in MATLAB 30-31

9 Conditional Statements in MATLAB 32-37

10 Loops in MATLAB 38-39

11 Plotting in MATLAB 40-43

12 Graphs in MATLAB 44-48

13 Polynomial in MATLAB 49-50

14 Algebra in MATLAB 51-54

15 Calculus in MATLAB 55-56

16 Certificate 57

17 Project made using c 58-60

2
BTCS 305-18 IT WORKSHOP FILE 2301695

Introduction to MATLAB:
MATLAB, short for MATrix LABoratory, is a high-level programming environment
developed by MathWorks, widely used for numerical computation, data analysis,
algorithm development, and visualization. Initially designed for matrix-based linear
algebra, MATLAB has evolved into a versatile tool supporting an extensive range of
engineering and scientific applications. At its core, MATLAB provides an intuitive
syntax, making it accessible for beginners while offering advanced features for
professionals. It integrates computation, visualization, and programming in a single
environment, enabling users to perform complex mathematical operations and create
comprehensive data visualizations with ease.

One of MATLAB’s distinguishing features is its interactive desktop environment,


which includes components such as the Command Window for executing commands,
the Workspace for managing variables, and the Editor for writing scripts and
functions. It also provides dedicated tools like the Figure Window for visualizing data
and the File Browser for managing projects. These features are complemented by a
vast library of built-in functions that simplify solving problems across various
domains, including signal processing, control systems, optimization, and machine
learning. MATLAB’s powerful visualization capabilities allow users to create 2D and
3D plots, animations, and interactive dashboards, making it an essential tool for
exploring and presenting data.

The platform is further enhanced by its toolboxes—specialized libraries designed to


extend MATLAB’s functionality in specific areas. Popular toolboxes include the
Signal Processing Toolbox, Image Processing Toolbox, Optimization Toolbox, and
Deep Learning Toolbox. Additionally, MATLAB integrates seamlessly with
Simulink, a complementary product used for model-based design and simulation of
dynamic systems, making it ideal for industries like automotive, aerospace, and
robotics. Beyond its built-in capabilities, MATLAB supports integration with
languages like C, C++, Java, and Python, and it facilitates hardware interfacing,
enabling the development of real-world applications.

MATLAB’s applications are vast and diverse. It is used in academia for teaching and
research, providing students and researchers with an intuitive platform to solve
equations, analyze datasets, and simulate physical systems. In industry, it is employed
for designing control systems, performing financial modeling, developing machine
learning algorithms, and conducting real-time signal analysis. Its ability to prototype
and deploy algorithms efficiently makes it a preferred choice for engineers and
scientists.

Despite its advantages, MATLAB has some limitations. Its proprietary nature and
high cost can be barriers for individuals and smaller organizations. Additionally, while
MATLAB excels at prototyping, it may not match the execution speed of lower-level
programming languages like C or Python for highly optimized applications.
Nevertheless, MATLAB’s versatility, extensive documentation, and strong

3
BTCS 305-18 IT WORKSHOP FILE 2301695

community support make it one of the most powerful tools for numerical computing
and algorithm development.

In summary, MATLAB is a comprehensive platform that bridges the gap between


theoretical concepts and practical applications, empowering users to solve complex
problems and innovate across a wide array of fields. Its user-friendly environment,
robust computational capabilities, and rich set of features ensure its continued
relevance in both academic and professional settings.

MATLAB is a powerful and versatile platform designed to meet the needs of researchers,
engineers, and scientists across a wide range of fields. Its popularity stems from its unique
combination of features, which make it ideal for tackling complex computational
problems, visualizing data, and developing algorithms. Below are the key reasons why
MATLAB stands out and why it is widely used:

1. Ease of Use

MATLAB offers an intuitive and user-friendly interface, making it accessible for


beginners while also catering to advanced users. Its high-level language allows users to
write programs and scripts with straightforward syntax, reducing the time needed to learn
and implement concepts. Built-in functions and toolboxes further simplify complex tasks.

2. Comprehensive Toolboxes

MATLAB’s extensive library of specialized toolboxes enables users to work on domain-


specific applications. For instance:

 The Signal Processing Toolbox aids in filtering, Fourier transforms, and spectral
analysis.
 The Image Processing Toolbox provides tools for image enhancement,
segmentation, and noise removal.
 The Optimization Toolbox helps solve mathematical optimization problems.
 The Deep Learning Toolbox supports neural network modeling and training.

3. Powerful Visualization

MATLAB excels in data visualization, allowing users to create a wide variety of plots,
graphs, and animations. From simple 2D plots to intricate 3D visualizations, MATLAB
makes it easy to explore data and present results in a visually appealing manner.
Interactive tools further enhance the analysis process by enabling real-time adjustments.

4. Interactive Development Environment

MATLAB’s integrated development environment (IDE) combines coding, debugging,


and visualization in one workspace. Key features like the Command Window for
immediate execution, the Editor for writing scripts, and the Workspace for variable
management streamline the workflow and enhance productivity.

4
BTCS 305-18 IT WORKSHOP FILE 2301695

5. Applications Across Diverse Fields

MATLAB is widely used across industries for tasks such as:

 Numerical computing: Solving linear equations, calculus, and differential


equations.
 Data analysis: Cleaning, processing, and visualizing large datasets.
 Machine learning: Building and training predictive models.
 Signal and image processing: Analyzing audio, video, and image data.
 Control systems: Designing and simulating dynamic systems.
 Financial modeling: Performing risk analysis and portfolio optimization.

6. Integration and Flexibility

MATLAB supports integration with other programming languages such as Python,


C/C++, and Java, providing flexibility for developers. It also facilitates hardware
integration, enabling real-time control systems and data acquisition.

7. Prototyping and Deployment

MATLAB is an excellent platform for rapid prototyping. Its efficient computation


capabilities allow users to test algorithms quickly before deploying them to production
environments. MATLAB Compiler and MATLAB Coder facilitate the deployment of
applications across different platforms.

8. Strong Community and Documentation

MATLAB has a robust community of users, along with extensive documentation and
tutorials provided by MathWorks. These resources make troubleshooting and learning
new skills easier.

9. Cross-Platform Compatibility

MATLAB runs on multiple operating systems, including Windows, macOS, and Linux,
ensuring compatibility for users in various environments.

Conclusion

MATLAB is a versatile and efficient tool for solving complex problems, visualizing data,
and implementing algorithms. Whether you're an engineer working on a control system, a
data scientist building predictive models, or a student learning linear algebra, MATLAB’s
capabilities make it an indispensable resource for computation and innovation. Its ease of
use, powerful features, and broad applications justify its widespread adoption in both
academic and professional settings.

5
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 1: BASICS OF MATLAB


MATLAB, an acronym for MATrix LABoratory, is a powerful computational tool
used for numerical computation, algorithm development, data analysis, and
visualization. It is designed to perform matrix operations efficiently, making it
particularly popular in engineering, science, and mathematics. This section provides a
detailed explanation of the basics of MATLAB, from its interface to core
functionalities.

MATLAB Environment: The MATLAB environment is an integrated platform


where users interact with tools to perform computations and develop algorithms.
Its primary components include:

1.Command Window: The Command Window is the interactive interface where users
execute commands and view immediate results.

Figure 1

Commands can be typed directly, making it suitable for quick calculations and testing
code snippets.

Example: a = 5; b = 10; c = a + b

Output: c = 15

6
BTCS 305-18 IT WORKSHOP FILE 2301695

2. Command History: In MATLAB, the Command History window is a log of all


the statements you've run in the current and previous sessions. It includes the time and
date of each session, along with the statements from that session.

Figure 2

Here are some things you can do with the Command History window:

Re-execute a line: Double-click the line in the Command History window.

Select a range of lines: Shift-click to select contiguous lines, or Command-click to


select non-contiguous lines.

Open the Command History window: Press the Up Arrow key (↑) or type command
history in the Command Window.

Display a specific statement: Type part of the statement at the prompt, then press the
Up Arrow key.

Keep the Command History window open: Click the action button, then select
Detach or Dock.

Save the Command History: Select File > Preferences > Command History, then set
the Saving option to Save after n commands.

You can also remove commands or figures from the Command History in MATLAB
Mobile.

7
BTCS 305-18 IT WORKSHOP FILE 2301695

3. Workspace: In MATLAB, the workspace is where you can store and manage
variables that you create or import into the program:

Figure 3

View and edit: Use the Workspace browser to view and edit the contents of your
workspace. You can also edit scalar variables directly in the Workspace browser.

Display statistics: Use the Workspace browser to display statistics for variables and
objects, such as minimum, maximum, and mean.

Save and load: Save your data to a compressed file with a .mat extension to use across
multiple sessions. You can restore saved data by loading a MAT-file back into
MATLAB.

Set preferences: Open Workspace preferences to specify Maximum array size to limit
the number of elements of arrays saved to a MATLAB script.

List variables: Use the who function to list variables in the workspace.

Analyze variable usage: Use the Model Explorer to analyze how a model uses variables.

There are also different types of workspaces in MATLAB, including:

Base workspace: Stores variables that you create at the command line. Variables in the
base workspace exist until you clear them or end your MATLAB session.

Model workspace: Initialized from a data source when the model is loaded. You can use
the Simulink Model Workspace object to perform tasks related to the model workspace.

8
BTCS 305-18 IT WORKSHOP FILE 2301695

4. Editor: MATLAB has two editors, the MATLAB Editor and the MATLAB Live
Editor:

MATLAB Editor: Allows users to enter commands, save scripts, write functions, set
breakpoints, and more. To open the editor, type edit or edit filename.

Figure 4

The MATLAB editor features include: syntax highlighting, auto-indentation, parenthesis


matching, code completion, debugging tools like breakpoints, step-through execution,
live editing with the ability to combine code, formatted text, and output visualizations
within a single document, and the option to publish live scripts as HTML, PDF, or other
formats; allowing users to create interactive and well-documented MATLAB code.

MATLAB Live Editor: Allows users to create interactive documents called Live Scripts
that combine code, output, and formatted text. Live Scripts can be shared with others as
PDFs, Word documents, HTML, or LaTeX documents.

The MATLAB Live Editor allows users to create interactive documents by combining
code, formatted text, images, equations, and hyperlinks, displaying output alongside the
code that produced it, enabling easy visualization and documentation of analysis while
allowing for interactive exploration of parameters through features like section-by-section
execution and live controls like sliders and dropdowns.

9
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 5

Key features of the MATLAB Live Editor:

Combined code and output: View results (plots, text, numerical values) directly next to
the code that generated them.

Formatted text: Add headings, paragraphs, lists, and other text formatting options to
enhance readability.

Equation editing: Insert mathematical equations using a dedicated editor or LaTeX


syntax.

Image integration: Embed images within the live script for visual explanation.

Section execution: Divide code into sections and run them individually, allowing for step-
by-step analysis.

Interactive controls: Add sliders, dropdowns, checkboxes, and other controls to modify
variables and observe changes in real-time.

Live tasks: Create interactive tasks that guide users through parameter exploration and
code generation.

Sharing capability: Export live scripts as various formats like PDF, HTML, or Markdown
for easy sharing with others.

Code generation: Automatically generate code based on adjustments made through


interactive controls.

10
BTCS 305-18 IT WORKSHOP FILE 2301695

Hide code view: Option to hide the code and only display the formatted text and outputs
for presentation purposes.

To create a Live Script, you can: Go to the Home tab>>Click New Live Script>>Add the
Census Data >>Divide your live script into sections.

5. Figure Window: A "figure window" in MATLAB refers to the individual graphical


window where plots, images, and other visual outputs are displayed; essentially, it's the
primary area on your screen where you see the results of your MATLAB code, created
using the "figure" function.

Figure 6

Key points about figure windows:

Creating a figure: To open a new figure window, use the command figure() in your
MATLAB code.

Manipulating properties: You can customize various aspects of a figure window like its
title, color, size, and more using property-value pairs when creating the figure.

11
BTCS 305-18 IT WORKSHOP FILE 2301695

Current figure: At any time, only one figure window is considered the "current figure,"
which is where new graphics commands will draw their output.

6. Current Folder: The current folder is a reference location that MATLAB uses to find
files. This folder is sometimes referred to as the current directory, current working folder,
or present working directory. To open the Current Folder browser if it is not currently
visible, on the Home tab, in the Environment section, click Layout. Then, in the Show
section, select Current Folder. In MATLAB Online™, the Current Folder browser is
called the Files panel. To show or hide the Files panel, click its icon in the sidebar.

Figure 7

7. MATLAB Syntax: MATLAB syntax is simple and designed for matrix and array
operations.
Example:

Figure 8

12
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 2: VARIABLES
Creating Variables: To create a variable enter the name of the variable in the command
window, followed by an = operator, and then assign it some values.

Figure 9

Output:

Figure 10

Assigning Vectors to Variables: A vector is a one-dimensional array of numbers.


Matlab allows you two types of vector:

Row Vector
Column Vector.

Row Vectors: These are created by enclosing numbers in square brackets separating
with either space or comma.

Example:

13
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 11

Output:

Figure 12

Column Vector: These are created by enclosing numbers in square brackets,


separating each number with ;(semicolon).

Example:

Figure 13

Output:

Figure 14

14
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 3: DATA TYPES


MATLAB is a platform which provides millions of Engineers and Scientists to
analyze data using programming and numerical computing algorithm and also help in
creating models. Data types are particular types of data items defined by the values
they can store in them, generally, in programming languages they are used.
In MATLAB we do not require any type of declaration statement, when it gets any
new variable name it creates the variable and allocates appropriate memory space to it
but if the variable name already exists it will replace the original content with new
content and allocate it to new storage space when required.

Syntax: variable name = a value (or an expression)

Example:

Figure 15

Output:

Figure 16

In MATLAB data can be stored in different types, numeric, text, complex number,
etc. To store these data MATLAB has different classes which have various
characteristics. MATLAB provides a total of 16 fundamental data types.

Figure 17

Logic Type: Logic types are True and false values that are represented with the
logical value 0 and 1. Any numerical value (non-complex) can be converted into a
logical representation.

15
BTCS 305-18 IT WORKSHOP FILE 2301695

Syntax: G = logical (x)

Example:

Figure 18

Output:

Figure 19

Char and String type: In MATLAB character and string array provide storage for
text type data. The strings are character array compared with the sequence of numbers
called a numeric array.

Syntax: s = ‘String’

Example:

Figure 20

16
BTCS 305-18 IT WORKSHOP FILE 2301695

Output:

Figure 21

Table: The table contains rows and column variables. Each variable can be of
different data types and different sizes, but each variable needs to have the same
number of rows. Range of functions are used to access data to create, edit, and read
the table data.

Example:

Figure 22

Output:

Figure 23

Cell: A cell array is a MATLAB data type that contains indexed data containers called
cells. Cells can contain any type of data, commonly contain character vectors of
different lengths, numbers, an array of numbers of any size. Sets of cells are enclosed
in () and access to the cells is done by using {} which is to create, edit or delete any
cell functions.

Example

Output:

Figure 24

Function Handles: Function Handles is majorly used in MATLAB is to pass a


function (numerical or char) to another function. Variables that are used to invoke
function indirectly can be named as a Function handle.

Example: To create a function handle to evaluate x^2 + y^2

17
BTCS 305-18 IT WORKSHOP FILE 2301695

Output:

Figure 25

18
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 4: OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. MATLAB is designed to operate primarily on whole matrices
and arrays. Therefore, operators in MATLAB work both on scalar and non-scalar
data. MATLAB allows the following types of elementary operations −

Arithmetic Operators: MATLAB allows two different types of arithmetic operations


 Matrix arithmetic operations
 Array arithmetic operations

Matrix arithmetic operations: These are same as defined in linear algebra. Array
operations are executed element by element, both on one-dimensional and
multidimensional array.

Examples:

Figure 26

Output:

Figure 27

19
BTCS 305-18 IT WORKSHOP FILE 2301695

Relational Operators: Relational operators can also work on both scalar and non-
scalar data. Relational operators for arrays perform element-by-element comparisons
between two arrays and return a logical array of the same size, with elements set to
logical 1 (true) where the relation is true and elements set to logical 0 (false) where it
is not.

Example:

Figure 28

Output:

Figure 29

Logical Operators: MATLAB offers two types of logical operators and functions
 Element-wise − These operators operate on corresponding elements of logical
arrays.
 Short-circuit − These operators operate on scalar and, logical expressions.

Example:

20
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 30

Output:

Figure 31

Bitwise Operations: Bitwise operators work on bits and perform bit-by-bit operation.
The truth tables for &, |, and ^ are as follows −

Examples:

21
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 32

Output:

Figure 33

22
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 5: MATRIX
A matrix is a two-dimensional array of numbers. In MATLAB, you create a matrix by
entering elements in each row as comma or space delimited numbers and using
semicolons to mark the end of each row.

Example:

Figure 34

Output:

Figure 35

Referencing the Elements of a Matrix:To reference an element in the mth row and
nth column, of a matrix mx,

Example:

Figure 36

Output: ans = 6

Deleting a Row or a Column in a Matrix: You can delete an entire row or column
of a matrix by assigning an empty set of square braces [] to that row or column.
Basically, [] denotes an empty array.

Example:

23
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 37

Output:

Figure 38

Addition and Subtraction of Matrices: You can add or subtract matrices. Both the
operand matrices must have the same number of rows and columns.

Example:

Figure 39

Output:

Figure 40

Division of Matrices: You can divide two matrices using left (\) or right (/) division
operators. Both the operand matrices must have the same number of rows and
columns.

Example:

24
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 41

Output:

Figure 42

Transpose of a Matrix: The transpose operation switches the rows and columns in a
matrix. It is represented by a single quote(').

Example:

Figure 43

Output:

Figure 44

25
BTCS 305-18 IT WORKSHOP FILE 2301695

Concatenating Matrices: You can concatenate two matrices to create a larger matrix.
The pair of square brackets '[]' is the concatenation operator.MATLAB allows two
types of concatenations

Horizontal concatenation
Vertical concatenation

Example:

Figure 45

Output:

Figure 46

Determinant of a Matrix: Determinant of a matrix is calculated using


the det function of MATLAB. Determinant of a matrix A is given by det(A).

Example:

Figure 47

26
BTCS 305-18 IT WORKSHOP FILE 2301695

Output:

Figure 48

Inverse of a Matrix: The inverse of a matrix A is denoted by A−1 such that the
following relationship holds

AA−1 = A−1A = 1

Example:

Figure 49

Output:

Figure 50

27
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 6: ARRAYS
Special Arrays in MATLAB: In this section, we will discuss some functions that
create some special arrays. For all these functions, a single argument creates a square
array, double arguments create rectangular array.The zeros() function creates an array
of all zeros

Example: Zeros(5)
Output:

Figure 51

A Magic Square: A magic square is a square that produces the same sum, when its
elements are added row-wise, column-wise or diagonally.The magic() function creates
a magic square array. It takes a singular argument that gives the size of the square.
The argument must be a scalar greater than or equal to 3.

Example: Magic(4)
Output:

Figure 52

Multidimensional Arrays: An array having more than two dimensions is called a


multidimensional array in MATLAB. Multidimensional arrays in MATLAB are an
extension of the normal two-dimensional matrix. Generally to generate a
multidimensional array, we first create a two-dimensional array and extend it.

Example:

28
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 53

Output:

Figure 54

Cell Array: Cell arrays are arrays of indexed cells where each cell can store an array
of a different dimensions and data types.The cell function is used for creating a cell
Example:

Figure 55

Output:

Figure 56

29
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 7: SCRIPTS AND FUNCTIONS


Scripts: A script file is an ordinary MATLAB file that could contain any code except
a class definition. See the following example which creates and displays a magic
square.

Example:

Figure 57

Output:

Figure 58

Functions: As seen in the previous section, a script file can contain a locally declared
function. Now, traditionally a function in MATLAB is defined more globally by
creating it in its specified file. A file that contains a function only needs to fulfill
following conditions:

Example:

Figure 59

Output:

30
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 60

31
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 8: CONDITIONAL STATEMENTS


Conditional statements are something that is very basic and important for every
programmer. There will be some situations where a program or a particular block has
to be executed only when a specific condition is True. These conditional statements
will be very handy and fruitful in such situations. These conditional statements work
as same as in other languages. However, syntax varies from language to language. The
following are the conditional statements that we can use in MATLAB.

if-end statement: An if-end statement is the simplest decision-making statement. It


decides whether a particular block of code has to be executed or not, based on the
given boolean condition. Only when the given condition is true, it executes the
statements inside the block otherwise not.

Syntax: if (condition)

% statement(s) will execute

% if the boolean expression is true

<statements>

End

Example:

Figure 61

Output:

Figure 62

if-else-end statement: In conditional if Statement the additional block of code is


merged as else statement which is performed when if the condition is false else
condition won’t be executed when if the condition is True.
32
BTCS 305-18 IT WORKSHOP FILE 2301695

Syntax: if (condition)

% statement(s) will execute

% if the boolean expression is true

<statement(s)>

else

<statement(s)>

% statement(s) will execute

% if the boolean expression is false

End

Example:

Figure 63

Output:

Figure 64

nested if-end Statement: There comes some situations where multiple conditions
have to be satisfied to execute a block of code then we use nested if-end statements.
This is nothing but another if condition(s) inside an if condition.

Syntax: if (condition)

% Executes when the boolean expression 1 is true

33
BTCS 305-18 IT WORKSHOP FILE 2301695

if (condition)

% Executes when the boolean expression 2 is true

End

Example:

Figure 65

Output:

Figure 66

if- elseif- elseif-else-end: An if statement can be followed by one (or more) optional
elseif and an else statement, which is very useful to test various conditions.

Syntax: if (condition)

% Executes when the expression 1 is true

<statement(s)>

elseif (condition)

% Executes when the boolean expression 2 is true

34
BTCS 305-18 IT WORKSHOP FILE 2301695

<statement(s)>

elseif (condition)

% Executes when the boolean expression 3 is true

<statement(s)>

else

% executes when the none of the above condition is true

<statement(s)>

End

Example:

Figure 67

Output:

Figure 68

Switch case: A switch block is familiar to if-elif-else-end statements. It works as


same as in other languages except for syntax. But there are few key differences
between them. A switch block conditionally executes one set of statements from

35
BTCS 305-18 IT WORKSHOP FILE 2301695

several choices. Each choice is covered by a case statement. A switch expression can
be any of the following.

Syntax: switch (condition)

case condition

<statements>

case (condition)

<statements> otherwise

<statements>

End

Example:

Figure 69

Output:

Figure 70

Nested Switch Case: This is similar to nested if statements. We can use switch as a
part of the statement inside a switch. Even if the case constants of the inner and outer
switch contain common values, no conflicts will arise.
36
BTCS 305-18 IT WORKSHOP FILE 2301695

Syntax: switch (condition)

case (condition)

<statements>

switch (condition)

case (condition)

<statements>end

case (condition)

<statements>

End

Example:

Figure 71

Output:

Figure 72

37
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 9: LOOPS
While Loop: While loop works same as it does in other common languages like
python, java etc. But here syntax varies from language to language. While loop is used
to execute a block of statements repeatedly until a given a condition is satisfied. And
when the condition becomes false, the line immediately after the loop in program is
executed.

Syntax: while expression

Statements

End

Example:

Figure 73

Output:

Figure 74

For loop: It is used when you know the number of iterations in advance. It's
particularly useful for iterating over arrays or performing a specific number of
repetitions.

38
BTCS 305-18 IT WORKSHOP FILE 2301695

Example:

Figure 75

Output:

Figure 76

We have one more way of using for loop, that is used to access array elements. Here
we assign an array directly to the for loop to access its elements through the iterator
variable (i.e., i or j etc).

Example:

Figure 77

Output:

Figure 78

39
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 10: PLOTTING


MATLAB is a powerful tool for data visualization, allowing you to create a wide
range of plots to understand and communicate insights from your data. By using
MATLAB's built-in plotting functions, you can visualize data in various forms, such
as line plots, scatter plots, bar charts, histograms, and many more.

Create a script file and type the following code

Figure 79

When you run the file, MATLAB displays the following plot

Figure 80

Let us take one more example to plot the function y = x2. In this example, we will
draw two graphs with the same function, but in second time, we will reduce the value
of increment. Please note that as we decrease the increment, the graph becomes
smoother.

Create a script file and type the following code:

40
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 81

When you run the file, MATLAB displays the following plot:

Figure 82

Adding Title, Labels, Grid Lines and Scaling on the Graph

MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and
also to adjust the axes to spruce up the graph.

Example:

Figure 83

41
BTCS 305-18 IT WORKSHOP FILE 2301695

Output:

Figure 84

Drawing Multiple Functions on the Same Graph

You can draw multiple graphs on the same plot. The following example demonstrates
the concept:

Example:

Create a script file and type the following code

Figure 85

Output:

42
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 86

43
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 11: GRAPHS


Vertical Bar-graphs: This plot draws bars at positions specified by the array “Year”
with the heights as specified in the array “Revenue”

Example:

Figure 87

Output:

Figure 88

44
BTCS 305-18 IT WORKSHOP FILE 2301695

Horizontal Bar Graph: This plot draws horizontal bars at positions specified by the
array “Year” with the lengths as specified in the array “Revenue”.

Example:

Figure 89

Output:

Figure 90

45
BTCS 305-18 IT WORKSHOP FILE 2301695

Pareto Charts: This plot shows vertical bars corresponding to the values of the data
in descending order of value. This also shows a curve made with the cumulative
values above each bar. In addition to this, the right side of the graph has a percentage
scale that shows how much percentage each bar contributes to the sum of all values.

Example:

Figure 91

Output:

Figure 92

46
BTCS 305-18 IT WORKSHOP FILE 2301695

Scatter Plot: This plot shows dots placed at the values given in the data. The Y-axis
is scaled from the lowest to the highest value in the data. The X-axis is scaled
similarly as in stem charts, from least to highest value.

Example:

Figure 93

Output:

Figure 94

47
BTCS 305-18 IT WORKSHOP FILE 2301695

Stairstep Plot: This plot shows a staircase-like structure with each step beginning at
the next value given in the data. Similar to the scatter plot, X and Y axes scale from
the lowest to the highest values given.

Example:

Figure 95

Output:

Figure 96

48
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 12: POLYNOMIALS


Evaluating Polynomials: The polyval function is used for evaluating a polynomial at
a specified value. For example, to evaluate our previous polynomial p, at x = 4, type
Example:

Figure 97

Output: ans=693
MATLAB also provides the polyvalm function for evaluating a matrix polynomial. A
matrix polynomial is a polynomial with matrices as variables.
Example:

Figure 98

Output:

Figure 99

Finding the Roots of Polynomials: The roots function calculates the roots of a
polynomial. For example, to calculate the roots of our polynomial p, type

Example:

Figure 100

49
BTCS 305-18 IT WORKSHOP FILE 2301695

Output:

Figure 101

Polynomial Curve Fitting: The polyfit function finds the coefficients of a


polynomial that fits a set of data in a least-squares sense. If x and y are two vectors
containing the x and y data to be fitted to a n-degree polynomial, then we get the
polynomial fitting the data by writing

Example:

Figure 102

Output:

Figure 103

50
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 13: Algebra


Solving Basic Algebraic Equations in MATLAB

The solve function is used for solving algebraic equations. In its simplest form, the
solve function takes the equation enclosed in quotes as an argument.

For example, let us solve for x in the equation x-5 = 0

Example:

Figure 104

Output: ans=5

Example:

Figure 105

Output: Y=5

Example:

Figure 106

Output: ans=5

If the equation involves multiple symbols, then MATLAB by default assumes that you
are solving for x, however, the solve function has another form

Example:

Figure 107

Output:

51
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 108

Solving Basic Algebraic Equations in Octave

The roots function is used for solving algebraic equations in Octave and you can write
above examples as follows

Example:

Figure 109

Output: ans=5

Example:

Figure 110

Output: Y=5

Solving Quadratic Equations in MATLAB

The solve function can also solve higher order equations. It is often used to solve
quadratic equations. The function returns the roots of the equation in an array.The
following example solves the quadratic equation x2 -7x +12 = 0. Create a script file
and type the following code

Figure 111

Output:

52
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 112

Solving Higher Order Equations in MATLAB

The solve function can also solve higher order equations. For example, let us solve a
cubic equation as (x-3)2(x-7) = 0

Output:

Figure 113

In case of higher order equations, roots are long containing many terms. You can get the
numerical value of such roots by converting them to double. The following example solves
the fourth order equation x4 − 7x3 + 3x2 − 5x + 9 = 0.

Example:

Figure 114

Output:

53
BTCS 305-18 IT WORKSHOP FILE 2301695

Figure 115

54
BTCS 305-18 IT WORKSHOP FILE 2301695

EXPERIMENT 14: CALCULUS


MATLAB provides various ways for solving problems of differential and integral
calculus, solving differential equations of any degree and calculation of limits. Best of
all, you can easily plot the graphs of complex functions and check maxima, minima
and other stationery points on a graph by solving the original function, as well as its
derivative.

Calculating Limits: MATLAB provides the limit function for calculating limits. In its
most basic form, the limit function takes expression as an argument and finds the limit
of the expression as the independent variable goes to zero.

Example:

Figure 116

Output:

Figure 117

Calculating Limits using Octave: Following is Octave version of the above example
using symbolic package, try to execute and compare the result

Example:

Figure 118

Output:

Figure 119

55
BTCS 305-18 IT WORKSHOP FILE 2301695

Verification of Basic Properties of Limits using Octave: Following is Octave


version of the above example using symbolic package, try to execute and compare the
result:

Example:

Figure 120

Output:

Figure 121

56
BTCS 305-18 IT WORKSHOP FILE 2301695

CERTIFICATE

Figure 122

57
BTCS 305-18 IT WORKSHOP FILE 2301695

PROJECT
BANK DATA MANAGEMENT SYSYTEM
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>
using namespace std;

class temp
{
int accNo;
char name[25];
char Fname[25];
char cnic[35];
char P_no[35];
char email[30];
float amount;
fstream file, file1;
int search;
int New_amount;
public:
void CreateAccount();
void DepositAmount();
void withdrawAmount();
void checkInfo();
} obj;

int main()
{
char option;
cout << "\tNOTE:::Enter your details without space" << endl;
cout << "\n\t\t..........:::MY BANK:::.........." ;
cout << "\n\t\t:: 1.Create New Account ::";
cout << "\n\t\t:: 2.Check Account Status ::";
cout << "\n\t\t:: 3.Deposit Amount ::";
cout << "\n\t\t:: 4.Withdraw Amount ::";
cout << "\n\t\t:: 5.EXIT ::";
cout << "\n\t\t::.............................::\n\t\t\t\t";
cout<<"Enter choice ;
cin >> option;
switch (option)
{

58
BTCS 305-18 IT WORKSHOP FILE 2301695

case '1':
obj.CreateAccount();
break;
case '2':
obj.checkInfo();
break;
case '3':
obj.DepositAmount();
break;
case '4':
obj.withdrawAmount();
break;
case '5':
system("exit");
break;
default:
cout << "Invalid Option";
}
}
void temp::CreateAccount()

{
srand(time(0));
accNo = rand() * rand() + rand() * rand();
cout << "Enter Your Name ::";
cin >> name;
cout << "\nEnter Your Father Name ::";
cin >> Fname;
cout << "\nEnter Your CNIC ::";
cin >> cnic;
cout << "\nEnter Your phone Number ::";
cin >> P_no;
cout << "\nEnter Your Email ::";
cin >> email;
cout << "\nEnter Your First Amount ::";
cin >> amount;
cout << endl;
cout << "\t\t\t\tACCOUNT NUMBER \t\t\t\t" << endl;
cout << "\t\t\t\t" << accNo << "\t\t\t\t" << endl;
cout << "Please Save IT" << endl;
file.open("Data.txt", ios::out | ios::app);
file << accNo << "\t" << name << "\t" << Fname << "\t" << cnic << "\t" << P_no << "\t"
<< email << "\t" << amount << "\n";
file.close();
}
void temp::DepositAmount()

59
BTCS 305-18 IT WORKSHOP FILE 2301695

{
cout << "Enter Your Account Number";
cin >> search;
fstream file, file1;
file.open("Data.txt", ios::in);
file1.open("Data1.txt", ios::out | ios::app);
file >> accNo >> name >> Fname >> cnic >> P_no >> email >> amount;

while (!file.eof())
{
if (accNo == search)
{
cout << "Account found Successfully" << endl;
cout << "Enter Amount TO Deposit" << endl;
cin >> New_amount;
cout << "ACCOUNT HOLDER NAME::" << name << endl;
cout << " Father Name::" << Fname << endl;
cout << "Email::" << email << endl;
cout << " CURRENT AMOUNT::" << amount << endl;
amount = amount + New_amount;
cout << " UPDATED AMOUNT::" << amount << endl;
file1 << accNo << "\t" << name << "\t" << Fname << "\t" << cnic << "\t" << P_no <<
"\t" << email << "\t" << amount << endl;
}
else
{
file1 << accNo << "\t" << name << "\t" << Fname << "\t" << cnic << "\t" << P_no <<
"\t" << email << "\t" << amount << endl;
}
file >> accNo >> name >> Fname >> cnic >> P_no >> email >> amount;
}
file.close();
file1.close();
remove("Data.txt");
rename("Data1.txt", "Data.txt");
}
void temp::withdrawAmount()
{
cout << "Enter Your ACCOUNT NUMBER::";
cin >> search;
file.open("Data.txt", ios::in);
file1.open("Data1.txt", ios::out | ios::app);
file >> accNo >> name >> Fname >> cnic >> P_no >> email >> amount;
while (!file.eof())
{
if (accNo == search)

60
BTCS 305-18 IT WORKSHOP FILE 2301695

{
cout << "Account found Successfully" << endl;
cout << "Enter Amount TO Wthdraw" << endl;
cin >> New_amount;
cout << "ACCOUNT HOLDER NAME::" << name << endl;
cout << " Father Name::" << Fname << endl;
cout << "Email::" << email << endl;
cout << " CURRENT AMOUNT::" << amount << endl;
amount = amount - New_amount;
cout << " UPDATED AMOUNT::" << amount << endl;
file1 << accNo << "\t" << name << "\t" << Fname << "\t" << cnic << "\t" << P_no <<
"\t" << email << "\t" << amount << endl;
}
else
{
file1 << accNo << "\t" << name << "\t" << Fname << "\t" << cnic << "\t" << P_no <<
"\t" << email << "\t" << amount << endl;
}
file >> accNo >> name >> Fname >> cnic >> P_no >> email >> amount;
}

file.close();
file1.close();
remove("Data.txt");
rename("Data1.txt", "Data.txt");
}
void temp::checkInfo()
{
cout << "Enter Your Account Number";
cin >> search;
file.open("Data.txt", ios::in);
file >> accNo >> name >> Fname >> cnic >> P_no >> email >> amount;
while (!file.eof())
{
if (accNo == search)
{
cout << "Account found Successfully" << endl;
cout << "\n\nACCOUNT NUMBER::" << accNo << endl;
cout << "NAME::" << name << endl;
cout << "Father Name::" << Fname << endl;
cout << "CNIC::" << cnic << endl;
cout << "PHONE NUMBER::" << P_no << endl;
cout << "Email::" << email << endl;
cout << "AMOUNT::" << amount << "/-" << endl;
}
file >> accNo >> name >> Fname >> cnic >> P_no >> email >> amount;

61
BTCS 305-18 IT WORKSHOP FILE 2301695

file.close();
}
OUTPUT:
fi

DATA STORED IN FILE:: “ DATA.txt ” file

62

You might also like