Matlab Varun
Matlab Varun
IT WORSKHOP
PRACTICAL FILE
BTCS 305-18
1
BTCS 305-18 IT WORKSHOP FILE 2301705
INDEX
S.NO CONTENTS PAGE NO SIGNATURE
1 Introduction to MATLAB 3-5
2
BTCS 305-18 IT WORKSHOP FILE 2301705
Introduction to MATLAB:
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
3
BTCS 305-18 IT WORKSHOP FILE 2301705
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
2. Comprehensive Toolboxes
• 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
BTCS 305-18 IT WORKSHOP FILE 2301705
immediate execution, the Editor for writing scripts, and the Workspace for variable
management streamline the workflow and enhance productivity.
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 2301705
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.
1.Command Window: The Command Window is the interactive interface where users
execute commands and view immediate results.
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 2301705
Here are some things you can do with the Command History window:
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 2301705
3. Workspace: In MATLAB, the workspace is where you can store and manage
variables that you create or import into the program:
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.
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 2301705
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.
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 2301705
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.
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.
Hide code view: Option to hide the code and only display the formatted text and outputs
for presentation purposes.
10
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
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.
Current figure: At any time, only one figure window is considered the "current figure,"
which is where new graphics commands will draw their output.
11
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
7. MATLAB Syntax: MATLAB syntax is simple and designed for matrix and array
operations.
Example:
12
BTCS 305-18 IT WORKSHOP FILE 2301705
VARIABLES
A variable in simple terms is a storage place that has some memory allocated to it.
Basically, a variable used to store some form of data. Different types of variables
require different amounts of memory and have some specific set of operations that can
be applied to them. The Matlab workspace store all the variables that you create or use
during a session.
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.
Output:
Note:
If you don’t put ‘;’ after the variable name, Matlab will display its content after hitting
enter.
If you don’t give any name to your variable by default Matlab name it with an answer.
By default, Matlab treats all variables as matrices if you write just 1 it will store it as
1×1 matrix.
13
BTCS 305-18 IT WORKSHOP FILE 2301705
To display the content of the Matlab variable you just need to type the name of the
variable, and it will show its content on Command-Line:
Example:
Output:
Row Vector
Column Vector.
Row Vectors: These are created by enclosing numbers in square brackets separating
with either space or comma.
Example:
14
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
Example:
Output:
Example:
Output:
15
BTCS 305-18 IT WORKSHOP FILE 2301705
Who command: Who lists in alphabetical order the names of all variables in the
currently active workspace. To use this command variables should be present in the
active workspace and memory allocated to each variable is necessary.
Example:
Output:
Example:
Output:
16
BTCS 305-18 IT WORKSHOP FILE 2301705
MATLAB supports a variety of variable types, each designed to handle specific data
types and operations. Numeric variables, including scalars, vectors, and matrices, are
essential for mathematical computations and data analysis. Character arrays and
strings allow you to work with textual data, while logical variables represent true or
false values. Cell arrays and structures provide versatile ways to organize and store
heterogeneous data.
MATLAB provides several functions for working with variables, including whos to
display information about variables in the workspace, clear to remove variables, and
save and load to save and load variables to and from files. By mastering these
functions, you can efficiently manage your workspace and organize your MATLAB
projects.
17
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
Example:
Output:
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.
18
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
Example:
Output:
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:
19
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
Numeric Type: Integer and floating-point data are in this type with the following
descriptions.
20
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Output:
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.
Syntax: T = table(ColumnName1,ColumnName2);
Example:
Output:
21
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
Syntax: c = { }
Example:
Output:
Structure: In structure data containers are used to group related data and their type,
which are called fields. Fields may contain any type of data. In structures, Data is
accessed using the dot notation.
Example:
Output:
22
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
Operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operations
• Set Operations
Arithmetic Operators
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.
The matrix operators and array operators are differentiated by the period (.) symbol.
However, as the addition and subtraction operation is same for matrices and arrays,
the operator is same for both cases. The following table gives brief description of the
operators –
Examples:
24
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
25
BTCS 305-18 IT WORKSHOP FILE 2301705
26
BTCS 305-18 IT WORKSHOP FILE 2301705
27
BTCS 305-18 IT WORKSHOP FILE 2301705
28
BTCS 305-18 IT WORKSHOP FILE 2301705
29
BTCS 305-18 IT WORKSHOP FILE 2301705
30
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
31
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Output:
32
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
33
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
Logical Operators
Example:
34
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
Apart from the above-mentioned logical operators, MATLAB provides the following
commands or functions used for the same purpose-
35
BTCS 305-18 IT WORKSHOP FILE 2301705
36
BTCS 305-18 IT WORKSHOP FILE 2301705
37
BTCS 305-18 IT WORKSHOP FILE 2301705
38
BTCS 305-18 IT WORKSHOP FILE 2301705
Bitwise Operations: Bitwise operators work on bits and perform bit-by-bit operation.
The truth tables for &, |, and ^ are as follows −
Examples:
Output:
MATLAB provides various functions for bit-wise operations like 'bitwise and',
'bitwise or' and 'bitwise not' operations, shift operation, etc.
39
BTCS 305-18 IT WORKSHOP FILE 2301705
Set Operations
MATLAB provides various functions for set operations, like union, intersection and
testing for set membership, etc.
40
BTCS 305-18 IT WORKSHOP FILE 2301705
41
BTCS 305-18 IT WORKSHOP FILE 2301705
==, ~=, <, >, <=, and >=, help us compare values and make logical decisions. They
are often used in conditional statements and control flow structures to guide the
execution of code based on specific conditions. Logical operators, such as &&, ||, and
~, enable us to combine logical expressions and evaluate their truth values. They are
indispensable for constructing complex logical conditions and implementing decision-
making processes.
MATLAB also provides a rich set of specialized operators for various applications.
Bitwise operators, such as bitand, bitor, bitxor, and bitcmp, allow us to manipulate
individual bits within binary numbers. These operators are useful in digital signal
processing, cryptography, and other fields that require low-level bit manipulation. The
colon operator, :, is a powerful tool for generating sequences of numbers, accessing
array elements, and reshaping matrices. It simplifies many common array operations
and provides a concise way to manipulate data.
When working with complex numbers, MATLAB offers specialized operators like i
and j to represent the imaginary unit. These operators enable us to perform complex
arithmetic operations, analyze complex-valued signals, and solve complex equations.
Additionally, MATLAB supports matrix operations, such as matrix multiplication,
inversion, and transposition, using operators like *, /, \, and '. These operators are
essential for linear algebra, numerical analysis, and machine learning.
By mastering the use of operators, you can write efficient, concise, and expressive
MATLAB code. Remember to consider the operator precedence and associativity
rules to ensure correct evaluation of expressions. Additionally, be mindful of the data
types involved in your calculations to avoid unexpected results. By effectively
combining operators with MATLAB's powerful functions and libraries, you can tackle
a wide range of computational challenges and unlock the full potential of this versatile
programming language.
42
BTCS 305-18 IT WORKSHOP FILE 2301705
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:
Output:
Referencing the Elements of a Matrix:To reference an element in the mth row and
nth column, of a matrix mx,
Example:
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:
Output:
43
BTCS 305-18 IT WORKSHOP FILE 2301705
Matrix Operations: In this section, let us discuss the following basic and commonly
used matrix operations
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:
Output:
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:
Output:
44
BTCS 305-18 IT WORKSHOP FILE 2301705
Scalar Operations of Matrices: When you add, subtract, multiply or divide a matrix
by a number, this is called the scalar operation.Scalar operations produce a new
matrix with same number of rows and columns with each element of the original
matrix added to, subtracted from, multiplied by or divided by the number.
Example:
Output:
Transpose of a Matrix: The transpose operation switches the rows and columns in a
matrix. It is represented by a single quote(').
Example:
45
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
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
When you concatenate two matrices by separating those using commas, they are just
appended horizontally. It is called horizontal concatenation.Alternatively, if you
concatenate two matrices by separating those using semicolons, they are appended
vertically. It is called vertical concatenation.
Example:
Output:
46
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Output:
Example:
47
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
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
The inverse of a matrix does not always exist. If the determinant of the matrix is zero,
then the inverse does not exist and the matrix is singular.Inverse of a matrix in
MATLAB is calculated using the inv function. Inverse of a matrix A is given by
inv(A).
Example:
Output:
MATLAB's matrix operations are highly optimized, allowing for efficient computations on
large datasets. Basic operations like addition, subtraction, multiplication, and division are
seamlessly performed on matrices, enabling you to solve linear equations, perform matrix
48
BTCS 305-18 IT WORKSHOP FILE 2301705
One of the key strengths of MATLAB is its ability to handle sparse matrices efficiently.
Sparse matrices, which contain many zero elements, are common in various applications,
including network analysis, finite element analysis, and machine learning. MATLAB's sparse
matrix data structures and operations allow you to work with large, sparse matrices without
compromising performance.
Beyond basic matrix operations, MATLAB offers a rich set of tools for matrix analysis and
visualization. You can easily compute eigenvalues and eigenvectors, perform singular value
decomposition, and analyze matrix properties. Additionally, MATLAB's plotting capabilities
allow you to visualize matrices as heatmaps, contour plots, or 3D plots, providing insights
into the underlying data and relationships.
Matrix operations in MATLAB are also essential for solving systems of linear equations.
MATLAB's \ operator provides a convenient way to solve linear systems, even for large and
complex problems. This operator automatically selects the most appropriate method, such as
Gaussian elimination or LU factorization, to efficiently solve the system.
49
BTCS 305-18 IT WORKSHOP FILE 2301705
Arrays:
All variables of all data types in MATLAB are multidimensional arrays. A vector is a
one-dimensional array and a matrix is a two-dimensional array.
We have already discussed vectors and matrices. In this chapter, we will discuss
multidimensional arrays. However, before that, let us discuss some special types of
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:
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:
50
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Output:
51
BTCS 305-18 IT WORKSHOP FILE 2301705
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
array. Syntax for the cell function is
C = cell(dim)
C = cell(dim1,...,dimN)
D = cell(obj)
52
BTCS 305-18 IT WORKSHOP FILE 2301705
Where,
Example:
Output:
Accessing Data in Cell Arrays: There are two ways to refer to the elements of a cell
array
• Enclosing the indices in first bracket (), to refer to sets of cells
• Enclosing the indices in braces {}, to refer to the data within individual cells
When you enclose the indices in first bracket, it refers to the set of cells.
53
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Output:
Example:
Output:
54
BTCS 305-18 IT WORKSHOP FILE 2301705
MATLAB provides a rich set of functions for creating, manipulating, and analyzing
arrays. You can create arrays using various methods, including direct assignment, the
zeros, ones, and rand functions, and the linspace and logspace functions for generating
linearly or logarithmically spaced arrays. Indexing and slicing techniques allow you to
access and extract specific elements or subsets of an array. You can use logical
indexing to select elements based on certain conditions, and linear indexing to access
elements using a single index.
By mastering arrays and their operations, you can efficiently solve a wide range of
problems in MATLAB. Whether you're working with numerical data, signal
processing, image analysis, or machine learning, arrays are the cornerstone of your
MATLAB toolkit. By understanding the different types of arrays, their indexing and
manipulation techniques, and advanced array operations, you can unlock the full
potential of MATLAB for a wide range of applications.
55
BTCS 305-18 IT WORKSHOP FILE 2301705
Script
Live Script
Class file
Now only the live script is the only one of these which has a different extension name;
all other three use the standard .m extension. In this article, we shall compare the
script and function files.
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:
Output:
Now, a script file can also contain a function definition in it. The syntax for the same
is
Code
Function Definitions
56
BTCS 305-18 IT WORKSHOP FILE 2301705
It is mandatory that the function definitions must be written after all the codes in the
script.
While declaring functions in a script file, keep the following things in mind:
Example:
Output:
57
BTCS 305-18 IT WORKSHOP FILE 2301705
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:
Output:
By effectively utilizing both scripts and functions, MATLAB users can streamline
their workflow, enhance code efficiency, and tackle complex computational problems
with ease.
58
BTCS 305-18 IT WORKSHOP FILE 2301705
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
• if-else-end
• nested-if-end
• if-elseif-elseif-else-end
• switch case
• nested switch case
Syntax: if (condition)
<statements>
End
Example:
Output:
59
BTCS 305-18 IT WORKSHOP FILE 2301705
Syntax: if (condition)
<statement(s)>
else
<statement(s)>
End
Example:
Output:
60
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Output:
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)
if (condition)
End
End
61
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Output:
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)
<statement(s)>
elseif (condition)
<statement(s)>
elseif (condition)
<statement(s)>
else
62
BTCS 305-18 IT WORKSHOP FILE 2301705
<statement(s)>
End
Example:
Output:
• Numbers
• Characters
• Strings
• Objects
63
BTCS 305-18 IT WORKSHOP FILE 2301705
case condition
<statements>
case (condition)
<statements>
otherwise
<statements>
End
Example:
Output:
64
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Output:
Example:
Output:
65
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
case (condition)
<statements>
switch (condition)
case (condition)
<statements>
…..
end
case (condition)
<statements>
End
Example:
66
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
Note:
Conditional statements empower us to write efficient and adaptable code. They enable
us to create programs that can handle diverse user interactions, respond to changing
data, and make intelligent decisions based on predefined criteria. Whether it's
determining user eligibility, validating input, or controlling the flow of program
execution, conditional statements provide the necessary tools to build robust and
intelligent software solutions.
67
BTCS 305-18 IT WORKSHOP FILE 2301705
Loops:
Loops are a fundamental programming construct that allows you to repeatedly execute
a block of code. MATLAB offers two primary types of loops: for loops and while
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.
Statements
End
Example:
Output:
68
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
Statements
End
Or
statements
end
Example:
Output:
Example:
69
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
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:
Output:
Iterating through strings is same as iterating through a range of numbers. Here we use
length() function to provide final value in for loop, and we can also use disp() function
to print the output.
Example:
70
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
For loops are ideal when you know the exact number of iterations beforehand. They
allow you to iterate through arrays, matrices, or sequences of numbers, performing
operations on each element. By controlling the loop index and step size, you can
customize the iteration process to suit your specific needs.
While loops, on the other hand, are more flexible and suitable for indefinite iterations.
They continue executing the code block as long as a specified condition remains true.
This makes them well-suited for tasks like user input validation, numerical
simulations, and optimization algorithms.
When using loops, it's crucial to pay attention to potential pitfalls like infinite loops
and inefficient coding practices. Always ensure that your loop conditions are well-
defined and that the loop will eventually terminate. Additionally, consider the
computational complexity of your loop and explore alternative approaches, such as
vectorization, to optimize performance.
In conclusion, loops are a powerful tool in MATLAB, enabling you to write concise
and efficient code. By understanding the differences between for and while loops and
employing best practices, you can effectively harness their capabilities to solve a wide
range of computational problems. Remember to consider vectorization techniques to
optimize your code and avoid unnecessary iterations, leading to more efficient and
elegant MATLAB solutions.
71
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
To plot the graph of a function, you need to take the following steps:
• Define x, by specifying the range of values for the variable x, for which the
function is to be plotted
• Define the function, y = f(x)
• Call the plot command, as plot(x, y)
Following example would demonstrate the concept. Let us plot the simple function y
= x for the range of values for x from 0 to 100, with an increment of 5.
When you run the file, MATLAB displays the following plot
72
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
When you run the file, MATLAB displays the following plot:
73
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
• The xlabel and ylabel commands generate labels along x-axis and y-axis.
• The title command allows you to put a title on the graph.
• The grid on command allows you to put the grid lines on the graph.
• The axis equal command allows generating the plot with the same scale factors
and the spaces on both axes.
• The axis square command generates a square plot.
Example:
74
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
You can draw multiple graphs on the same plot. The following example demonstrates
the concept:
Example:
75
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
MATLAB provides eight basic color options for drawing graphs. The following table
shows the colors and their codes
76
BTCS 305-18 IT WORKSHOP FILE 2301705
Example
Output:
The axis command allows you to set the axis scales. You can provide minimum and
maximum values for x and y axes using the axis command in the following way −
Example:
77
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
Generating Sub-Plots
When you create an array of plots in the same figure, each of these plots is called a
subplot. The subplot command is used for creating subplots.
subplot(m, n, p)
where, m and n are the number of rows and columns of the plot array and p specifies
where to put a particular plot.
Each plot created with the subplot command can have its own characteristics.
Following example demonstrates the concept –
Example:
78
BTCS 305-18 IT WORKSHOP FILE 2301705
y = e−1.5xsin(10x)
y = e−2xsin(10x)
Output:
79
BTCS 305-18 IT WORKSHOP FILE 2301705
The plot function serves as the cornerstone of MATLAB's plotting arsenal, allowing
you to create basic line plots with ease. By customizing line styles, colors, markers,
and line widths, you can tailor plots to suit specific needs and preferences. Adding
axis labels, titles, and grid lines further enhances plot readability and interpretation.
MATLAB's diverse range of plotting functions caters to various data types and
visualization requirements. Scatter plots, bar charts, histograms, pie charts, and
contour plots are just a few examples of the rich repertoire available. These functions
enable you to explore data distributions, compare categorical data, visualize spatial
relationships, and identify trends and patterns.
For more complex data analysis and visualization, MATLAB offers advanced plotting
techniques. 3D plots, surface plots, and polar plots provide powerful tools for
visualizing multidimensional data and understanding underlying structures. By
combining these techniques with interactive features, you can gain deeper insights and
explore data from multiple perspectives.
80
BTCS 305-18 IT WORKSHOP FILE 2301705
Graphs:
MATLAB is a powerful tool for creating a wide range of graphs and visualizations. It
provides a rich set of functions and customization options to help you effectively
communicate your data. Here are some common types of graphs you can create in
MATLAB:
Vertical Bar-graphs: This plot draws bars at positions specified by the array “Year”
with the heights as specified in the array “Revenue”
Example:
Output:
81
BTCS 305-18 IT WORKSHOP FILE 2301705
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:
82
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
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:
83
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
Bar Graphs (both vertical and horizontal) and Pareto charts can be used to represent
data such as marks of a student in different subjects, rainfall received in different
months, and many other data sets.
Stem Charts: This plot shows a straight line with a bulb at the top (or bottom for
negative values) corresponding to the values given in the data. The X-axis is scaled
from the least to the highest value given. which may result in the first and last value
being situated right at the border of the graph.
Example:
84
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
85
BTCS 305-18 IT WORKSHOP FILE 2301705
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:
Output:
86
BTCS 305-18 IT WORKSHOP FILE 2301705
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:
Output:
87
BTCS 305-18 IT WORKSHOP FILE 2301705
The plot function serves as the foundation of MATLAB's plotting arsenal, enabling
you to create basic line plots with ease. By customizing line styles, colors, markers,
and line widths, you can tailor plots to suit specific needs and preferences. Adding
axis labels, titles, and grid lines further enhances plot readability and interpretation.
MATLAB's diverse range of plotting functions caters to various data types and
visualization requirements. Scatter plots, bar charts, histograms, pie charts, and
contour plots are just a few examples of the rich repertoire available. These functions
enable you to explore data distributions, compare categorical data, visualize spatial
relationships, and identify trends and patterns.
For more complex data analysis and visualization, MATLAB offers advanced plotting
techniques. 3D plots, surface plots, and polar plots provide powerful tools for
visualizing multidimensional data and understanding underlying structures. By
combining these techniques with interactive features, you can gain deeper insights and
explore data from multiple perspectives.
88
BTCS 305-18 IT WORKSHOP FILE 2301705
Polynomials:
MATLAB provides a powerful and efficient way to work with polynomials. A
polynomial is a mathematical expression consisting of variables, coefficients, and
exponents. In MATLAB, polynomials are represented as row vectors containing the
coefficients in descending order of powers. For example, the polynomial p(x) = 3x^3 -
2x^2 + 5x - 1 can be represented as the vector p = [3 -2 5 -1].
Example:
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:
Output:
89
BTCS 305-18 IT WORKSHOP FILE 2301705
The roots function calculates the roots of a polynomial. For example, to calculate the
roots of our polynomial p, type
Example:
Output:
The function poly is an inverse of the roots function and returns to the polynomial
coefficients.
Example:
Output:
90
BTCS 305-18 IT WORKSHOP FILE 2301705
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:
Output:
91
BTCS 305-18 IT WORKSHOP FILE 2301705
The polyval function allows you to evaluate a polynomial at specific points or arrays
of points, enabling you to analyze the behavior of the polynomial and its relationship
with independent variables. By utilizing the roots function, you can determine the
values of the independent variable that make the polynomial equal to zero, providing
insights into the polynomial's zeros and critical points.
The poly function plays a crucial role in generating the coefficients of the
characteristic polynomial of a matrix, which is essential for various linear algebra
applications, such as eigenvalue and eigenvector analysis. Additionally, the conv and
deconv functions enable you to perform polynomial multiplication and division,
respectively, facilitating the manipulation and simplification of polynomial
expressions.
Polynomial fitting, a powerful technique for modeling data, is made possible by the
polyfit function. This function allows you to fit a polynomial of a specified degree to a
set of data points, providing a mathematical model that can be used for prediction,
interpolation, and extrapolation.
The polyder and polyint functions enable you to perform polynomial differentiation
and integration, respectively. These operations are fundamental to calculus and have
applications in various fields, including physics, engineering, and economics. By
combining these functions with other MATLAB tools, you can solve differential
equations, analyze the behavior of dynamical systems, and optimize functions.
92
BTCS 305-18 IT WORKSHOP FILE 2301705
Algebra:
MATLAB, a powerful mathematical computing environment, is exceptionally well-
suited for linear algebra. It provides a rich set of functions and tools to efficiently
solve systems of linear equations, perform matrix operations, and analyze linear
transformations. By leveraging MATLAB's matrix-oriented syntax and optimized
algorithms, you can streamline complex algebraic computations and gain deeper
insights into mathematical models.
With MATLAB, you can easily define and manipulate matrices, perform basic
arithmetic operations like addition, subtraction, multiplication, and division, and
calculate determinants, inverses, and eigenvalues. Additionally, MATLAB offers
specialized functions for solving systems of linear equations, such as linsolve and
mldivide, and for finding eigenvalues and eigenvectors, such as eig.
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.
Example:
Output:
ans=5
Example:
Output:
93
BTCS 305-18 IT WORKSHOP FILE 2301705
Y=5
Example:
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:
Output:
The roots function is used for solving algebraic equations in Octave and you can write
above examples as follows
Example:
Output:
ans=5
Example:
Output:
94
BTCS 305-18 IT WORKSHOP FILE 2301705
Y=5
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
Output:
The following example solves the quadratic equation x2 -7x +12 = 0 in Octave. Create
a script file and type the following code:
Output:
95
BTCS 305-18 IT WORKSHOP FILE 2301705
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:
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:
Output:
96
BTCS 305-18 IT WORKSHOP FILE 2301705
The following example solves the fourth order equation x4 − 7x3 + 3x2 − 5x + 9 = 0.
Example:
Output:
97
BTCS 305-18 IT WORKSHOP FILE 2301705
The solve function can also be used to generate solutions of systems of equations
involving more than one variables. Let us take up a simple example to demonstrate
this use.
5x + 9y = 5
3x – 6y = 4
Output:
We have a little different approach to solve a system of 'n' linear equations in 'n'
unknowns. Let us take up a simple example to demonstrate this use.
5x + 9y = 5
3x – 6y = 4
Such a system of linear equations can be written as the single matrix equation Ax = b,
where A is the coefficient matrix, b is the column vector containing the right-hand
side of the linear equations and x is the column vector representing the solution as
shown in the below program:
Example:
98
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
The expand and the collect function expands and collects an equation respectively.
The following example demonstrates the concepts:
When you work with many symbolic functions, you should declare that your variables
are symbolic.
Example:
Output:
99
BTCS 305-18 IT WORKSHOP FILE 2301705
You need to have symbolic package, which provides expand and the collect function
to expand and collect an equation, respectively. The following example demonstrates
the concepts:When you work with many symbolic functions, you should declare that
your variables are symbolic but Octave has different approach to define symbolic
variables. Notice the use of Sin and Cos, which are also defined in symbolic
package.Create a script file and type the following code:
Example:
100
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
The factor function factorizes an expression and the simplify function simplifies an
expression. The following example demonstrates the concept:
Example:
Output:
101
BTCS 305-18 IT WORKSHOP FILE 2301705
MATLAB's matrix-oriented syntax and optimized algorithms make it an ideal tool for
solving systems of linear equations. Functions like linsolve and mldivide provide
efficient and accurate solutions, even for large systems. Additionally, MATLAB's
ability to handle sparse matrices significantly reduces memory usage and computation
time, making it suitable for large-scale simulations and data analysis.
102
BTCS 305-18 IT WORKSHOP FILE 2301705
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.
This chapter will deal with problems of calculus. In this chapter, we will discuss pre-
calculus concepts i.e., calculating limits of functions and verifying the properties of
limits.
In the next chapter Differential, we will compute derivative of an expression and find
the local maxima and minima on a graph. We will also discuss solving differential
equations.
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.
For example, let us calculate the limit of a function f(x) = (x3 + 5)/(x4 + 7), as x tends
to zero.
Example:
Output:
The limit function falls in the realm of symbolic computing; you need to use
the syms function to tell MATLAB which symbolic variables you are using. You can
also compute limit of a function, as the variable tends to some number other than zero.
To calculate lim x->a(f(x)), we use the limit command with arguments. The first being
the expression and the second is the number, that x approaches, here it is a.
103
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Output:
Example:
Output:
Following is Octave version of the above example using symbolic package, try to
execute and compare the result
Example:
Output:
104
BTCS 305-18 IT WORKSHOP FILE 2301705
Algebraic Limit Theorem provides some basic properties of limits. These are as
follows:
Let us calculate the limits of the functions as x tends to 5, of both functions and verify
the basic properties of limits using these two functions and MATLAB.
Example:
Output:
105
BTCS 305-18 IT WORKSHOP FILE 2301705
Following is Octave version of the above example using symbolic package, try to
execute and compare the result:
Example:
106
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
When a function has a discontinuity for some particular value of the variable, the limit
does not exist at that point. In other words, limits of a function f(x) has discontinuity
at x = a, when the value of limit, as x approaches x from left side, does not equal the
value of the limit as x approaches from right side.
This leads to the concept of left-handed and right-handed limits. A left-handed limit is
defined as the limit as x -> a, from the left, i.e., x approaches a, for values of x < a. A
right-handed limit is defined as the limit as x -> a, from the right, i.e., x approaches a,
for values of x > a. When the left-handed limit and right-handed limit are not equal,
the limit does not exist.
f(x) = (x - 3)/|x - 3|
We will show that limx->3 f(x) does not exist. MATLAB helps us to establish this fact
in two ways −
The left-handed and right-handed limits are computed by passing the character strings
'left' and 'right' to the limit command as the last argument.
107
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Output:
108
BTCS 305-18 IT WORKSHOP FILE 2301705
The diff function allows you to calculate the derivative of a function symbolically or
numerically. This enables you to analyze the rate of change of a function, identify
critical points, and determine the concavity of the function. The int function, on the
other hand, calculates the indefinite or definite integral of a function, providing
insights into the area under the curve, the accumulation of quantities, and the solution
of differential equations.
MATLAB's symbolic math toolbox also empowers you to solve differential equations
symbolically, providing exact solutions when possible. For more complex differential
equations or those without analytical solutions, MATLAB's numerical methods, such
as Euler's method, Runge-Kutta methods, and finite difference methods, can be
employed to approximate solutions.
109
BTCS 305-18 IT WORKSHOP FILE 2301705
• Object
• Class
• Polymorphism
• Inheritance
• Abstraction
• Encapsulation
Now let’s dive into some examples to understand the above concepts better.
Class:
A Class is a template/blueprint defined by a user using which objects are created. It
comprises of a set of attributes and methods which are used for object entities. A
Constructor is a method/function, defined with the same name of the class, and it
initializes the classes with certain values passed through the calling function (i.e
Constructor). Defining a constructor is optional as in many other languages.
MATLAB syntax is quite peculiar compared to other conventional programming
languages.
.....
end
Parameters:
110
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Save the above code as adder.m file and access it with commands from command
prompt/another matlab file. Let’s access the above code by giving some commands
from another matlab file and observe the output to understand it better.
111
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
Object:
An Object is a logical entity that interacts with the user-defined class by invoking
methods/functions. We can create as many objects as you want. Every object will
have two characteristics i.e., state and behavior. These characteristics vary with every
object as per the situation. For example, dog is an object/identity. It’s loyalty, sleep,
walk, etc are behaviors and size, color, breed, etc comes under the state.
Inheritance:
The title itself suggests that inheritance is nothing but inheriting/acquiring all the
properties, such as attributes, methods, etc, of parent/base class. The class that is
derived from a base class is called as Sub Class/Child Class and it inherits all the
properties of its parents class. Superclass is the class that is being inherited by the
subclass. The importance of the inheritance is the code reusability such as using the
parent class’s attributes, methods, etc. Let’s dive into an example to understand the
inheritance concept better.
112
BTCS 305-18 IT WORKSHOP FILE 2301705
.......
End
Example:
Save the above code as Animal.m and this is our superclass. Let us see subclass now.
113
BTCS 305-18 IT WORKSHOP FILE 2301705
Save the above code as Lion.m and this is our subclass. Now let’s access the parent
class using subclass object and observe the output.
Output:
Polymorphism:
The mechanism of defining a function with the name of the already existed function is
known as polymorphism. Simply we call it as overriding. MATLAB doesn’t support
overloading a function. The polymorphic functions perform different operations with
the same name based on the passed arguments and user-defined logic.
Super class:
Save the above code as superClass.m and let’s also see the derived class code.
Derived Class:
114
BTCS 305-18 IT WORKSHOP FILE 2301705
Save the above code as derivedClass.m and let’s observe the output.
Output:
Abstraction:
An Abstract class depicts the functionality performed by a group of classes. It hides
important or unnecessary data and shows only the essential components. For instance,
A mobile can be viewed but not its inner components. All the methods, attributes that
are being used by the subclasses are declared in the abstract class. A concrete subclass
is derived from abstract class to use its properties. An abstract can’t be instantiated. It
can only be inherited. All the methods declared in the abstract class must be
redefined/overridden in the subclass.
Syntax:
.....
115
BTCS 305-18 IT WORKSHOP FILE 2301705
End
Example:
Save the above code as superClass.m and let’s see the code for the base class.
116
BTCS 305-18 IT WORKSHOP FILE 2301705
Save the above code as derivedClass.m and execute the code and observe the output
by giving a couple of commands.
Output:
Encapsulation:
Prerequisite: MATLAB documentation of Value and Handle Classes
Encapsulation is a mechanism of enclosing the data and the code together in a single
class/unit. It provides security to the data by prohibiting the limit to other classes. One
can access or modify the data of a class only by using getters and setters methods. We
need to inherit handle class to implement encapsulation in MATLAB as it doesn’t
return duplicate and modified objects and also handles the errors.
MATLAB –
Save the above code as superClass.m and let’s observe the output by giving a couple
of commands.
Output:
117
BTCS 305-18 IT WORKSHOP FILE 2301705
118
BTCS 305-18 IT WORKSHOP FILE 2301705
Error Handling:
Error handling is a way that allows you to manage and respond to errors or
unexpected situations that might occur while your MATLAB program is running.
Instead of letting your program crash and give unnecessary results, you can gracefully
handle errors, provide feedback to the user, and even attempt to recover from the
issue.
The most common type of errors that can occur while executing the code are syntax
errors, runtime errors, or logical errors.
Syntax Errors
A syntax error in MATLAB occurs when there is a mistake in the structure or syntax
of your code.
Example:
In this code, there's a syntax error because a and b are not defined or assigned any
values before they are used in the calculation. MATLAB expects these variables to be
defined or assigned values before they can be used in expressions. To correct this
syntax error, you should define or assign values to a and b before using them.
Runtime Errors
A runtime error in MATLAB occurs when your code is running, but it encounters a
problem during execution that prevents it from completing successfully.
Example:
119
BTCS 305-18 IT WORKSHOP FILE 2301705
Logical Errors
In this code, the loop runs from 1 to n, adding the values from 1 to n to sum. However,
if we want to calculate the sum of numbers from 1 to n, the code is incorrect because
it will include n in the sum. The loop should be running from 1 to n-1.
Error handling in matlab helps us to take care of the syntax, runtime and logical issues
if any while executing the code. Error handling will tell the correct reason for any
failure of executing the code to the user.
Here’s a simple example of how to use display error message to users in matlab:
error(msg,A) : helps to create an error message with placeholders (e.g., %s, %d) that
can be replaced with actual values from variables.
Example:
In this example, if the value is greater than 100, it will trigger the error with the
custom message "Value entered is greater than expected. Please use a smaller value."
Output:
120
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
In this example, if age is greater than 100, the error message will include the value
100 in place of the %d placeholder, resulting in the message: "Error: Age value is too
high. It should be below 100."
Output:
For warning messages we can make use of the warning() in-built function available in
matlab.
121
BTCS 305-18 IT WORKSHOP FILE 2301705
Example: In the example below a warning message saying: "The value of x (10) is
larger than 5." wil be displayed. The %d is a formatting character, and the value of x
gets inserted into the warning message at that position.
Output:
Example: Let us use warning() method to just display the warning message as shown
in the example below
Output:
Example: To know the status of the warning you can just type warning and enter in
the matlab command window.
Output:
122
BTCS 305-18 IT WORKSHOP FILE 2301705
Example:
Once you execute the above code and type warning , you should see the message ‘All
warnings have the state 'off'.
Output:
The try and catch blocks in MATLAB help manage potential errors that may occur
during code execution.
Example of try/catch
The example shows code that attempts to execute the test() function inside the try
block. If an error occurs during the execution of test(), MATLAB will catch the error
and jump to the catch block, where it displays an error message that includes details
about the error using disp(['Error occurred: ' exception.message]);
When you execute the same in matlab command window the output is:
123
BTCS 305-18 IT WORKSHOP FILE 2301705
Conclusion: Robust error handling is essential for writing reliable and maintainable
MATLAB code. By implementing effective error handling techniques, you can
prevent unexpected program crashes, identify and address issues promptly, and
provide informative error messages to users. MATLAB offers a variety of tools and
techniques to help you achieve this goal.
The error function is a powerful tool for generating custom error messages. By using
the error function, you can provide specific information about the error condition,
helping users to diagnose and fix problems more efficiently. Additionally, you can
customize error messages to match your specific application and provide context-
sensitive information.
The warning function is useful for signaling non-critical errors or potential issues that
may not necessarily prevent the program from executing. By using the warning
function, you can alert users to potential problems without interrupting the program's
flow. This can be helpful for identifying and addressing issues during development
and testing.
The assert function is a valuable tool for verifying assumptions and conditions within
your code. By using the assert function, you can check for invalid input, unexpected
output, or other conditions that may indicate errors. If an assertion fails, an error is
thrown, allowing you to identify and address the underlying issue.
124
BTCS 305-18 IT WORKSHOP FILE 2301705
Experiments:
Experiment1: Write a program to print your own name
Output:
125
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
126
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
127
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
128
BTCS 305-18 IT WORKSHOP FILE 2301705
Experiment5: Write a Program to Find the roots and determine the nature of the
roots.
Output:
129
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
130
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
131
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
132
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
133
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
134
BTCS 305-18 IT WORKSHOP FILE 2301705
Experiment 11: Write a Program to find the Eigen values and Eigen vectors.
Output:
135
BTCS 305-18 IT WORKSHOP FILE 2301705
136
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
137
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
138
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
139
BTCS 305-18 IT WORKSHOP FILE 2301705
140
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
141
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
142
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
143
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
144
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
145
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
146
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
147
BTCS 305-18 IT WORKSHOP FILE 2301705
Experiment 22: Write a Program to make Scatter Plot with a Color Gradient.
Output:
148
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
149
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
150
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
151
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
152
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
153
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
154
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
155
BTCS 305-18 IT WORKSHOP FILE 2301705
30) Write a Program for Simulation of Projectile Motion with consideration of Air
Resistance
156
BTCS 305-18 IT WORKSHOP FILE 2301705
Output:
157