MATLAB - TELCOMA Training path so that MATLAB will find the files easily. Copyright © TELCOMA. All...
Transcript of MATLAB - TELCOMA Training path so that MATLAB will find the files easily. Copyright © TELCOMA. All...
Copyright © TELCOMA. All Rights Reserved
What is MATLAB?MATLAB
High Level Languages such as C, PASCAL,
FORTRAN etc.
Assembly Language
MATLAB
1. Is an abbreviation to MATrix
LABoratory.
2. Is compatible with OOPs.
3. Provides easy access to
matrix softwares developed
by LINPACK and EISPACK
projects.
Copyright © TELCOMA. All Rights Reserved
Key Features of MATLAB...
1. It is a high-level language for numerical computation, visualization and
application development.
2. It also provides an interactive environment for iterative exploration,
design and problem solving.
3. It provides built-in graphics for visualizing data and tools for creating
custom plots.
Copyright © TELCOMA. All Rights Reserved
Key Features of MATLAB
4. It provides tools for building applications with custom graphical
interfaces.
5. It provides functions for integrating MATLAB based algorithms with
external applications and languages such as C, Java, .NET and Microsoft
Excel.
Copyright © TELCOMA. All Rights Reserved
Student Edition of MATLAB...
1. The professional and student editions of MATLAB ® are very similar.
2. Student editions are available for Microsoft Windows, Mac OSX, and
Linux operating systems.
3. It can be purchased from college bookstores or online from The
MathWorks at www.mathworks.com.
4. The MathWorks packages its software in groups called releases.
5. New versions are released every 6 months.
Copyright © TELCOMA. All Rights Reserved
Student Edition of MATLAB
6. The release number is the same for both the student and professional
edition, but the student version may lag the professional version by
several months.
7. Toolboxes other than those included with the student edition may be
purchased separately.
8. The biggest difference between the professional and student editions is
the command prompt, which is >> in the professional version and EDU>>
in the student edition.
Copyright © TELCOMA. All Rights Reserved
Problem Solving in Engineering and Science
1. State the problem .
2. Describe the input values (knowns) and the required outputs (unknowns).
3. Develop an algorithm to solve the problem. In computer applications, this
can often be accomplished with a hand example .
4. Solve the problem.
5. Test the solution .
Copyright © TELCOMA. All Rights Reserved
Introduction
MATLAB environment consists of
following main parts
1. Command Window
2. Command History
3. Workspace
4. Current Folder
5. Editor Window
Copyright © TELCOMA. All Rights Reserved
Command Window
1. Main window in MATLAB.
2. Used to enter variables.
3. Used to run functions and
M-file scripts.
4. All commands are typed after
command prompt “>>”.
Copyright © TELCOMA. All Rights Reserved
Command History
1. Statements entered in
command window are logged
in Command History.
2. View and search previously
run statements.
3. Copy and execute selected
statements.
Copyright © TELCOMA. All Rights Reserved
Workspace...
1. List all variables used as long
as MATLAB has opened.
2. Type “who” in command
window to list all the
commands used.
3. Type “whos” to list all the
commands with current
values, dimensions, etc.
Copyright © TELCOMA. All Rights Reserved
Workspace
4. “clear” command is used to
clear all the variables from
workspace.
5. Save all the variables and data
to text file (.mat file) to use it
for later.
Copyright © TELCOMA. All Rights Reserved
Current Folder
1. Lists all m files, etc. available
in current directory.
2. Set working folder as current
directory or as a part of the
search path so that MATLAB
will find the files easily.
Copyright © TELCOMA. All Rights Reserved
Editor
1. Used to create scripts and
m-files.
2. Click the “New Script” button
in the Toolbar.
Copyright © TELCOMA. All Rights Reserved
“Help” System...
1. Type “help” in command
window to go through various
topics.
2. Type “help elfun” (Elementary
Math Function), and MATLAB
will list all the functions
according to specific
category.
Copyright © TELCOMA. All Rights Reserved
“Help” System...3. “help<function_name>”
command is used to get
specific help about this
function.
4. To open the help window on
the specific topic of interest,
use “doc<topic>” command.
Copyright © TELCOMA. All Rights Reserved
“Help” System
5. help keyword is used to get
help for a specific function,
but lookfor command is used
to search for all functions, etc.
with a specific keyword.
6. Example: >>lookfor plot
Copyright © TELCOMA. All Rights Reserved
Introduction...
1. Defined with assignment operator, “=”.
2. Can be assigned without declaring their type and their type can
change.
3. Values can come from constants, computation involving values of
other variables, or from the output of a function.
4. Note that MATLAB is case sensitive! The variables x and X are not the
same.
Copyright © TELCOMA. All Rights Reserved
Introduction
5. Semicolon is used to suppress the output of the line that it concludes
and not to terminate commands.
Copyright © TELCOMA. All Rights Reserved
Built-in Commands
Name Description
i , j Used for complex numbers, e.g., z=2+4i
pi
inf ∞, infinity
NaN Not A Number
Copyright © TELCOMA. All Rights Reserved
Naming a variable uniquely...1. To avoid choosing a name for
a new variable that might
conflict with a name already in
use, check for any
occurrences of the name
using the which command.
Format: which -all variable_name
Copyright © TELCOMA. All Rights Reserved
2. The iskeyword command is also
used to list all reserved names.
3. These reserved names can’t be
assigned to any variable(s).
4. If anyone accidentally assign any
of these names, use clear
command to reset it back to
normal.
Naming a variable uniquely
Copyright © TELCOMA. All Rights Reserved
Task: Basic OperationType following commands in command window:
>>y=16;
>>z=3
1. When semicolon is used, no output will be displayed.
2. Some functions display output even if semicolon is used, like
disp, plot, etc
Copyright © TELCOMA. All Rights Reserved
Built-in Functions...
Function Description Example
help Displays the help information available >>help
help<function> Displays help about a specific function >>help plot
clc Clear the command window >>clc
clear Clear variables and functions from memory >>clear
format Set output format
Copyright © TELCOMA. All Rights Reserved
Function Description Example
who, whos Lists all variables in the active workspace >>who>>whos
size Size of arrays, matrices >>x=[1 2 ; 3 4];>>size(x)
length Length of a vector >>x=[1:1:10];>>length (x)
disp Displays text or array >>x=[1 2 ; 3 4];>>disp(x)
Built-in Functions...
Copyright © TELCOMA. All Rights Reserved
Function Description Example
plot To create a plot >>x=[1:1:10];>>plot (x)>>y=cos (x);>>plot (x,y)
rand Creates a random number, vector or matrix >>rand>>rand (2,1)
max Find the largest number in a vector >>x=[1:1:10]>>max (x)
Built-in Functions...
Copyright © TELCOMA. All Rights Reserved
Function Description Example
min Find the smallest number in a vector >>x=[1:1:10]>>min (x)
mean Average or mean value >>x=[1:1:10]>>mean (x)
std Standard deviation >>x=[1:1:10]>>std (x)
To read more about these functions, use “help<function_name>” command.
Built-in Functions...
Copyright © TELCOMA. All Rights Reserved
Introduction1. These are basic elements in MATLAB as well as in control
design theory.
2. A general matrix A may be written like this:
A= a11 ------ a1m
: ------ : Rnxm
an1------ anm
Copyright © TELCOMA. All Rights Reserved
Forming a matrix
1. In MATLAB, vectors and matrices will be typed as:
A= 1 2
3 4
2. To separate rows, semicolon “;” is used.
3. To separate columns, comma “,” or space “ ” is used.
or
Copyright © TELCOMA. All Rights Reserved
Selecting matrix elements
To get specific part of a
matrix, type as follows:
or
or
Copyright © TELCOMA. All Rights Reserved
Forming matrix from 2 vectors
`A matrix can also be created
from 2 vectors X and Y as:
Copyright © TELCOMA. All Rights Reserved
Colon Notation
It is very useful to create the
vectors as:
x=[xi:dx:xf]
where, xi is starting value,
xf is final value, and
dx is increment.
Copyright © TELCOMA. All Rights Reserved
Delete rows and columns
Rows and columns can be
deleted from a matrix using just a
pair of square brackets [].
A= 0 1
-2 -3
Copyright © TELCOMA. All Rights Reserved
Naming Conversions
While creating variables and
constants, create a name that is
not already exists by using “which”
command.
Copyright © TELCOMA. All Rights Reserved
Large or Small Numbers
To write large or small
numbers, like 2 x 10^5, 7.5 x 10^-8
“e” notation is used as:
Copyright © TELCOMA. All Rights Reserved
Line Continuation
Large arrays,split the row
across several command lines by
using the line continuation
operator “...”.
Copyright © TELCOMA. All Rights Reserved
Multiple commands on same line
Type several commands on
the same line to save space.
Copyright © TELCOMA. All Rights Reserved
Basic operations
Basic matrix operations are:
+ Addition
- Subtraction
* Multiplication
/ Division
^ Power
Copyright © TELCOMA. All Rights Reserved
Array Operations...
In this the basic matrix operations can be modified for
element-by-element operations by preceding the operator with a period.
+ Addition
- Subtraction
.* Multiplication
./ Division
.^ Power
Copyright © TELCOMA. All Rights Reserved
Array Operations...
Given:
A= a11 a12 B= b11 b12
a21 a22 b21 b22
Then
A.*B= a11b11 a12b12
a21b21 a22b22
Copyright © TELCOMA. All Rights Reserved
Introduction
1. It is a branch of mathematics
2. Concerned with the study of matrices, vectors, vector spaces (also
called linear spaces), linear maps (also called linear transformations),
and systems of linear equations.
3. Type “help matfun” (Matrix functions - numerical linear algebra) for
more information or type “help elmat” (Elementary matrices and matrix
manipulation).
Copyright © TELCOMA. All Rights Reserved
Functions for Linear Algebra...
Function Description Example
rank Provides an estimate of the number of linearly independent rows or columns of any matrix.
>>A=[1 2; 3 4]>>rank(A)
det Find determinant of a square matrix >>A=[1 2;3 4]>>det(A)
inv Find inverse of square matrix >>A=[1 2;3 4]>>inv(A)
Copyright © TELCOMA. All Rights Reserved
Function Description Example
eig Find eigenvalues of a square matrix >>A=[1 2; 3 4]>>eig(A)
ones Creates an array or matrix with only ones >>ones(2)>>ones(2,1)
eye Creates an identity matrix >>eye(2)
diag Find diagonal elements in a matrix >>A=[1 2;3 4]>>diag(A)
Functions for Linear Algebra
Copyright © TELCOMA. All Rights Reserved
1. Vector x is given as:
x= x1
x2
x3 ϵ Rn
:
xn
2. “Transpose” of vector x is given as:
x’= [ x1 x2 x3 --- xn ] ϵ R1xn
Vectors...
Copyright © TELCOMA. All Rights Reserved
3. The “Length” of vector x:
||x||= √x’x = √x1^2+x2^2+..+xn^2
4. “Orthogonality” is given as:
x’y=0
Vectors
Copyright © TELCOMA. All Rights Reserved
1. Matrix A is given as:
A= a11 ----- a1m
: ------ : ϵ Rnxm
an1 ----- anm
Matrices...
Copyright © TELCOMA. All Rights Reserved
2. “Transpose” of matrix A is given as:
A= a11 ------- an1
: ------ : ϵ Rmxn
a1m ----- anm
Matrices...
Copyright © TELCOMA. All Rights Reserved
3. The Diagonal elements of matrix
A is the vector:
diag(A)= a11
a22 ϵ Rp=min(m,n)
:
app
Matrices...
Copyright © TELCOMA. All Rights Reserved
4. The Diagonal matrix ⋀ is given by:
1 0 ---- 0
⋀= 0 2 --- 0 ϵ Rnxn
: : --- :
0 0 ---- n
Matrices...
Copyright © TELCOMA. All Rights Reserved
5. The Identity matrix I is given as:
1 0 ----- 0
I= 0 1 ----- 0 ϵ Rnxm
: : ----- :
0 0 ----- 1
Matrices
Copyright © TELCOMA. All Rights Reserved
Given matrices A ϵ Rnxm and B ϵ
Rmxp , then
C= AB ϵ Rnxp
where
Cjk=∑ aji bik
Matrix Multiplication...
n
i=1
Copyright © TELCOMA. All Rights Reserved
Note that n [ A ] m [ B ] = n [ C ]
Also
AB = BA
A(BC) = (AB)C
(A+B)C = AC+BC
C(A+B) = CA+CB
m p p
Matrix Multiplication
Copyright © TELCOMA. All Rights Reserved
Given matrices A ϵ Rnxm and B ϵ
Rnxm , then
C= A+B ϵ Rnxm
Matrix Addition
Copyright © TELCOMA. All Rights Reserved
Given a matrix A ϵ Rnxn , then
det(A) =|A|
Given 2x2 matrix:
A= a11 a12 ϵ R2x2
a21 a22
Then det(A) = |A| = a11 a22 - a21 a12
Determinant...
Copyright © TELCOMA. All Rights Reserved
Note that
det (AB) = det(A) det(B)
and
det(A’) = det(A)
Determinant
Copyright © TELCOMA. All Rights Reserved
5. Inverse Matrices: The inverse of quadratic matrix A ϵ Rnxn is
defined by:
A
if
AA = A A = I
Inverse Matrices...
-1
-1 -1
Copyright © TELCOMA. All Rights Reserved
For 2x2 matrix
Inverse Matrices
A= a11 a12 ϵ R2x2
a21 a22
Then A is given by
A = 1 a11 -a12 ϵ R2x2
det (A) -a21 a11
-1
-1
Copyright © TELCOMA. All Rights Reserved
Given A ϵ Rnxn , then eigenvalues
is defined as:
det( I - A) = 0
Eigenvalues
Copyright © TELCOMA. All Rights Reserved
7. Solving linear equations: Given
following equations:
x1 + 2x2 = 5
3x1 + 4x2 = 6
7x1 + 8x2 = 9
To find the solution, backlash
operator “\” is used.
Solving Linear Equations
Copyright © TELCOMA. All Rights Reserved
1. Input to a script will come from a data file that has been created by
another source.
2. It is useful to be able to store output in an external file that can be
manipulated and/or printed later.
3. There are basically three different operations, or modes on files. Files
can be: read from, written to, and appended to.
Introduction...
Copyright © TELCOMA. All Rights Reserved
4. Writing to a file means writing to a file from the beginning. Appending
to a file is also writing, but starting at the end of the file rather than the
beginning.
5. Use the load function to read and the save function to write to files.
Introduction
Copyright © TELCOMA. All Rights Reserved
1. The save command can be
used to write data from a matrix
to a data file, or to append to a
data file. The format is:
save filename matvarname -ascii
The “-ascii” qualifier is used
when creating a text or data file.
Writing Data to a File...
Copyright © TELCOMA. All Rights Reserved
2. The type command can be
used to display the contents of
the file.
3. Note that if the file already
exists, the save command will
overwrite the file.
4. Save always writes from the
beginning of a file.
Writing Data to a File
Copyright © TELCOMA. All Rights Reserved
Once a text file exists, data can
be appended to it.
The format is the same as the
preceding, with the addition of the
qualifier “-append”.
Appending Data to a Data File
Copyright © TELCOMA. All Rights Reserved
1. It is accomplished using load.
Once a file has been created, it
can be read into a matrix
variable.
2. If the file is a data file, the load
command will read from the file
“filename.ext”
Reading from a File...
Copyright © TELCOMA. All Rights Reserved
3. The load command works only if there are the same number of values
in each line so that the data can be stored in a matrix, and the save
command only writes from a matrix to a file.
Reading from a File
Copyright © TELCOMA. All Rights Reserved
1. Scripts or m-files are text files containing MATLAB code.
2. Editor is used to create a file containing the same statements written at command line.
3. Files are saved under a name ends with “.m”.
4. Both scripts and functions are created using MATLAB Editor.
Introduction
Copyright © TELCOMA. All Rights Reserved
1. A collection of commands
that will be executed in
command window.
2. Used for automate repetitive
tasks.
Scripts...
Copyright © TELCOMA. All Rights Reserved
3. Sequence of MATLAB commands is created in the Editor which will be saved as m-file.
4. Push the “Run” button to run a program.
5. Errors in code are displayed by some color symbols to right in the Editor.
Scripts...
Copyright © TELCOMA. All Rights Reserved
6. An m-file will be opened or
edited by using the open
button in the toolbar.
7. An alternative is to type
“Edit<name of m-file>” from
Command window.
Scripts
Copyright © TELCOMA. All Rights Reserved
1. Operate on information (inputs) fed into them and return outputs.
2. Have a separate workspace and internal variables.
3. User-defined functions work the same as the built-in functions.
4. Function is defined by using following syntax:
function outputs = function_name (inputs)
% documentation
Functions...
Copyright © TELCOMA. All Rights Reserved
5. First line of a function starts with
the keyword function.
6. It gives the function name and
order of arguments.
7. To separate words lowercase is
used, and not spaces.
Functions...
Copyright © TELCOMA. All Rights Reserved
9. The name of the m-file and of
the function should be the same.
Functions...
Copyright © TELCOMA. All Rights Reserved
10. In order to read the information
of the function type
“help<function name>” in the
command window.
Functions
Copyright © TELCOMA. All Rights Reserved
1. It is a very important and powerful feature in MATLAB.
2. Plot functions: some useful functions for creating plots are:
Introduction...
Function Description Example
plot Generates a plot. >>x=[0:0.01:1]’>>y=x.*x>>plot(x,y)
figure Create a new figure window. >>figure>>figure(1)
Copyright © TELCOMA. All Rights Reserved
Introduction...
Function Description Example
subplot Create subplots in a figure. Subplot (m,n,p) breaks the figure window into mxn matrix of small axis, selects the pth axis for the current plot.
>>subplot(2,2,1)
grid Creates grid lines in a plot. “grid on” adds major grid lines to the current plot and “grid off” removes major and minor grid lines.
>>grid>>grid on>>grid off
Copyright © TELCOMA. All Rights Reserved
Introduction...
Function Description Example
axis Control axis scaling and appearance. “axis([xmin xmax ymin ymax])” sets the limits for x and y axis.
>>axis([xmin xmax ymin ymax])>>axis off>>axis on
title Add title to current plot >>title (‘This is a title’)
xlabel Add label to x axis >>xlabel (‘time’)
ylabel Add label to y axis >>ylabel (‘temperature’)
Copyright © TELCOMA. All Rights Reserved
Introduction
Function Description Example
legend Creates a legend in the corner (or at specified position) of the plot.
>>legend(‘temperature’)
hold Freezes the current plot, so that the additional plots can be overlaid.
>>hold on>>hold off
Type “help graphics” in command window for more information.
Copyright © TELCOMA. All Rights Reserved
Here are some examples to use
the different plot functions.
Example 1:
Plot Functions...
Copyright © TELCOMA. All Rights Reserved
Plotting multiple data set in one
graph.
Plot Multiple Data Set
Copyright © TELCOMA. All Rights Reserved
Displaying multiple plots in one
figure- “subplot”
Syntax: subplot (m,n,p)
n
m
Subplot
p=1 p=2
p=3 p=3
Copyright © TELCOMA. All Rights Reserved
Customizing: various functions
can be used to customize the plot,
such as, title, xlabel, ylabel, etc.
Customizing a Plot...
Copyright © TELCOMA. All Rights Reserved
1. Line styles:
Customizing a Plot...
Specifier Line Style
- Solid line (Default)
-- Dashed line
: Dotted line
-. Dash-dot line
2. Colors:
Specifier Color Specifier Color
r Red m Magenta
g Green y Yellow
b Blue k Black
c Cyan w White
Copyright © TELCOMA. All Rights Reserved
3. Marker specifiers:
Customizing a Plot
Specifier Marker Type Specifier Marker Type
+ Plus sign v Downward-pointing triangle
о Circle > Right-pointing triangle
* Asterisk < Left-pointing triangle
. Point s Square
^ Upward-pointing triangle x Cross
Copyright © TELCOMA. All Rights Reserved
1. The loglog uses logarithmic
scales for both the x and y axes.
2. semilogy uses a linear scale for
the x-axis and a logarithmic
scale for the y-axis.
Logarithmic Plots...
Copyright © TELCOMA. All Rights Reserved
3. semilogx uses a logarithmic
scale for the x-axis and a linear
scale for the y-axis.
Logarithmic Plots
Copyright © TELCOMA. All Rights Reserved
1. The bar function draws a bar
chart.
2. barh draws a horizontal bar
chart.
Other Plots...
Copyright © TELCOMA. All Rights Reserved
3. area draws the plot as a
continuous curve and fills in
under the curve that is created.
4. stem draws a stem plot.
Other Plots...
Copyright © TELCOMA. All Rights Reserved
5. For a matrix, the bar and barh
functions will group together the
values in each row.
Other Plots...
Copyright © TELCOMA. All Rights Reserved
6. Note that MATLAB groups
together the values in the first
row and then in the second row.
7. It cycles through colors to
distinguish the bars.
8. The ‘stacked’ option will stack
the values.
Other Plots
Copyright © TELCOMA. All Rights Reserved
1. It is a particular type of bar chart
that shows the frequency of
occurrence of values within a
vector.
2. It uses bins to collect values that
are in given ranges.
3. hist function is used to create a
histogram.
Histogram
Copyright © TELCOMA. All Rights Reserved
1. comet function is used to
animate a plot.
2. Movie function can also be used
to display recorded movie
frames.
3. The frames are captured in a
loop using function getframe,
and are stored in a matrix.
Animation
or
Copyright © TELCOMA. All Rights Reserved
1. Functions used for 2D plots are
used to create 3D plots with ‘3’
at the end; like, plot3, bar3,
bar3h, pie3, comet3, stem3, etc.
3D Plots...
Copyright © TELCOMA. All Rights Reserved
2. The meshgrid function can be
used to create (x,y) points for
which z=f(x,y); then the x,y, and z
matrices can be passed to mesh
or surf.
3D Plots
Copyright © TELCOMA. All Rights Reserved
1. These are two-dimensional
representations of
three-dimensional surfaces.
2. The contour and surfc
commands are used to create
the plot.
Contour Plots
Copyright © TELCOMA. All Rights Reserved
1. A two-dimensional shaded map
is generated over a grid.
2. A sample function called peaks
that generates the x , y , and z
matrices of an interesting
surface that looks like a
mountain range.
Pseudo Color Plots
Copyright © TELCOMA. All Rights Reserved
Different loops can be used in MATLAB such as:
If-else statement
Switch and case statement
For loop
While loop
Introduction
Copyright © TELCOMA. All Rights Reserved
1. “if” statement evaluates a logical expression and executes a group of
statements when the expression is true.
2. The optional “elseif” and else keywords provide for the execution of
alternate groups of statements.
3. An “end” keyword, which matches the “if”, terminates the last group of
statements.
4. The groups of statements are delineated by the four keywords- no
braces or brackets are involved.
If-else statement...
Copyright © TELCOMA. All Rights Reserved
The general syntax is as follows:
if expression1
statements1
elseif expression2
statements2
else
statements3
end
If-else statement...
Copyright © TELCOMA. All Rights Reserved
Example :
Note that “if n==5” is used and
not “if n=5”
If A and B are scalars only then
“if A == B, ...” works, but if A and B are
matrices this might not work as
expected.
If-else statement
Copyright © TELCOMA. All Rights Reserved
Operators...
Mathematical Operator Description MATLAB Operator
< Less Than <
≤ Less Than or Equal To <=
> Greater Than >
≥ Greater Than or Equal To >=
= Equal To ==
≠ Not Equal To ~=
Copyright © TELCOMA. All Rights Reserved
1. “switch” statement executes a group of statements based on the value
of a variable or expression.
2. The keywords case and otherwise delineated the groups.
3. Only the first matching case is executed.
4. There must always be an end to match the switch.
Switch and Case statement...
Copyright © TELCOMA. All Rights Reserved
The general syntax is as follows:
switch variablecase case_value1
statements1case case_value2
statements2...
otherwisestatements
end
Switch and Case statement...
Copyright © TELCOMA. All Rights Reserved
1. “For” loop repeats a group of statements a fixed, predetermined number of times.
2. A matching end delineates the statements.
The general syntax is as follows:
for variable = initval:endvalstatements
...statementsend
For Loop...
Copyright © TELCOMA. All Rights Reserved
1. “While” loop repeats a group of statements an indefinite number of
times under control of a logical condition.
2. A matching end delineates the statements.
The general syntax is as follows:
while expression
statements
end
While Loop...
Copyright © TELCOMA. All Rights Reserved
1. The break command can be
used to terminate a loop
prematurely (while the
comparison in the first line is still
true).
2. A break statement will cause
termination of the smallest
enclosing while or for loop.
Break and Continue...
Copyright © TELCOMA. All Rights Reserved
3. The continue command is
similar to break ; however,
instead of terminating the loop,
the program just skips to the
next pass.
Break and Continue
Copyright © TELCOMA. All Rights Reserved
1. In these constructs the loop is
entered, calculations are
processed, and a decision is
made at some arbitrary point in
the loop whether or not to exit.
2. Then additional calculations are
processed and the loop repeats.
Midpoint Break Loop
Copyright © TELCOMA. All Rights Reserved
3. This strategy can be used either with a for loop or a while loop.
Midpoint Break Loop
Copyright © TELCOMA. All Rights Reserved
1. There are various Math functions in MATLAB: exp, sqrt, log, etc. 2. Various statistics functions in MATLAB are: mean, max, min, std, etc.3. MATLAB also offers lots of Trigonometric functions e.g., sin, cos, tan, etc.4. Complex numbers are important in modelling and control theory which
is defined as; z = a + ib or z = a + jb where imaginary unit (i/j) is i=√-1.5. MATLAB represents polynomials as row arrays containing coefficients
ordered by descending powers.
Introduction
Copyright © TELCOMA. All Rights Reserved
Creates a function that calculates the following mathematical exp.
z=3x^2+√(x^2+y^2) +ln(x)
Test with different values of x and y.
Simple Math Function
Copyright © TELCOMA. All Rights Reserved
1. MATLAB has built-in functions for many statistics.
2. min and max functions also return the index of the smallest or largest value.
3. If there is more than one occurrence, it returns the first.
Statistics...
Copyright © TELCOMA. All Rights Reserved
4. For matrices, the min and max functions operate columnwise by default.
Statistics...
Copyright © TELCOMA. All Rights Reserved
5. The arithmetic mean of a data set is what is usually called the average of the values.
6. For a matrix, the mean function operates columnwise.
7. To find the mean of each row, the dimension of 2 is passed as the second argument to the function
Statistics...
Copyright © TELCOMA. All Rights Reserved
8. Harmonic Mean: It is calculated by using harmmean function.
9. Geometric Mean: It is calculated by using geomean function.
Statistics...
Copyright © TELCOMA. All Rights Reserved
10. Variance and standard deviation are ways of determining the spread of the data.
11. The built-in function to calculate the variance is called var.
12. The standard deviation can be found either as the sqrt of the variance or using std.
Statistics...
Copyright © TELCOMA. All Rights Reserved
13. The mode of a data set is the value that appears most frequently.
14. The built-in function in MATLAB for this is called mode.
Statistics...
Copyright © TELCOMA. All Rights Reserved
15. The median is defined only for a data set that has been sorted first, meaning that the values are in order.
16. The function in MATLAB is called median.
Statistics
Copyright © TELCOMA. All Rights Reserved
1. These include union, intersect, unique, setdiff, and setxor.
2. All of these functions can be useful when working with data sets.
Set Operations...
Copyright © TELCOMA. All Rights Reserved
3. The function ismember receives two vectors as input arguments, and returns a logical vector that is the same length as the first argument.
4. Contains logical 1 for true if the element in the first vector is also in the second, or logical 0 for false if not.
Set operations...
Copyright © TELCOMA. All Rights Reserved
5. The issorted function will return logical 1 for true if the argument is sorted in ascending order (lowest to highest), or logical 0 for false if not.
Set operations
Copyright © TELCOMA. All Rights Reserved
Create various trigonometric functions and plot them on same figure.
Trigonometric Functions
Copyright © TELCOMA. All Rights Reserved
Complex no. is defined as:
z = a + ib or z = a + jb
The complex conjugate of z is defined as:
z* = a - ib
Complex Numbers
Copyright © TELCOMA. All Rights Reserved
It is expressed as:
p(x)=p1x^n+p2x^(n-1)+---+pn+pn+1
where p1,p2,p3,... are the coefficients of polynomial.
Polynomial, p(x)=-5.45x^4+3.2x^2+8x+5.6 will be written as shown.
Polynomials
Copyright © TELCOMA. All Rights Reserved
MATLAB Functions...
Function Description Example
i,j Imaginary unit. As basic imaginary unit SQRT(-1), i and j are used to enter complex numbers.
>>z=2+4i>>z=2+4j
abs The absolute value of elements of x. When x is complex, abs(x) is the complex modulus (magnitude) of the elements of x.
>>z=2+4i>>abs(z)
angle Phase angle, in radians. >>z=2+4i>>angle(z)
Copyright © TELCOMA. All Rights Reserved
MATLAB Functions...
Function Description Example
imag Complex imaginary part. >>z=2+4i>>b=imag(z)
real Complex real part. >>z=2+4i>>a=real(z)
conj Complex conjugate >>z=2+4i>>z_con=conj(z)
Copyright © TELCOMA. All Rights Reserved
MATLAB Functions
Function Description Example
complex Construct complex result from real and imaginary parts
>>a=2>>b=3>>z=complex(a,b)
Copyright © TELCOMA. All Rights Reserved
1. MATLAB’s symbolic capability is based on the MuPad software,
originally produced by SciFace Software.
2. SciFace was purchased by the Mathworks in2008.
3. The MuPad engine is part of the symbolic toolbox.
4. A MuPad notebook is created by typing mupad at command prompt.
Introduction
Copyright © TELCOMA. All Rights Reserved
1. Symbolic mathematics is used regularly in math, engineering, and
science classes.
2. It is often preferable to manipulate equations symbolically before
substituting values for variables.
3. Before solving any equation(s), there is a need to create some symbolic
variables.
4. Simple symbolic variables can be created in two ways.
Creating Symbolic Variables...
Copyright © TELCOMA. All Rights Reserved
5. To create the symbolic variable x, type either
x = sym (‘x’)
Or
syms x
Both techniques set the character 'x' equal to the symbolic variable x .
Creating Symbolic Variables...
Copyright © TELCOMA. All Rights Reserved
6. Note that in the workspace
window both x and y are listed
as symbolic variables and the
array size for each is 1 x 1.
Creating Symbolic Variables...
Copyright © TELCOMA. All Rights Reserved
7. The syms command is
particularly convenient, because
it can be used to create multiple
symbolic variables at the same
time.
8. The sym function can also be
used to create either an entire
expression or an entire equation.
Creating Symbolic Variables
Copyright © TELCOMA. All Rights Reserved
1. The Ezplot function: The
symbolic toolbox includes a
group of functions that allow
you to plot symbolic functions.
The most basic is ezplot.
Symbolic Plotting...
Copyright © TELCOMA. All Rights Reserved
2. Other plots: The 3D surface
plotting functions (ezmesh,
ezmeshc, ezsurf, and ezsurfc)
are used that mirror the
functions used in numeric
plotting options.
Symbolic Plotting
Copyright © TELCOMA. All Rights Reserved
A function called diff is used to
find the derivative of a symbolic
expression.
Differentiation
Copyright © TELCOMA. All Rights Reserved
A function called int is used to
find the integral of a symbolic
expression.
Integration
Copyright © TELCOMA. All Rights Reserved
1. Differential equations contain
both the dependent variable and
its derivative with respect to the
independent variable.
2. The symbolic toolbox includes a
function called dsolve that
solves differential equations,
that is, it solves for y in terms of
t.
Differential Equation
Copyright © TELCOMA. All Rights Reserved
The matlab-Function function
converts a symbolic expression into
an anonymous function.
Convert Expressions to Functions
Copyright © TELCOMA. All Rights Reserved
Linear interpolation can be
performed with the interp1 function.
Linear Interpolation
Copyright © TELCOMA. All Rights Reserved
A smoother curve can be
created by using the cubic spline
interpolation technique, included in
the interp1 function.
Cubic Spline Interpolation
Copyright © TELCOMA. All Rights Reserved
1. The simplest way to model a set of data is as a straight line.
2. To plot the data, draw a straight line through the data points to get a
rough model of the data’s behavior.
3. This process is sometimes called “eyeballing it”—meaning that no
calculations were done, but it looks like a good fit.
4. It is seen that several of the points appear to fall exactly on the line, but
others are off by varying amounts.
Linear Regression...
Copyright © TELCOMA. All Rights Reserved
5. In order to compare the quality
of the fit of this line to other
possible estimates, the
difference between the actual
y-value and the value calculated
from the estimate has found.
6. This difference is called the
residual.
Linear Regression...
Copyright © TELCOMA. All Rights Reserved
7. The linear regression technique
uses an approach called least
squares fit to compare how well
different equations model the
behavior of the data.
8. It is accomplished with the
polyfit function.
Linear Regression...
Copyright © TELCOMA. All Rights Reserved
1. It is used to get the best fit by
minimizing the sum of the
squares of the deviations of the
calculated values from the data.
2. The polyfit function allows to do
this easily.
Polynomial Regression
Copyright © TELCOMA. All Rights Reserved
1. The polyval function requires
two inputs.
2. The first is a coefficient array,
such as that created by polyfit.
3. The second is an array of input
values for which output values
are calculated.
Polyval Function
Copyright © TELCOMA. All Rights Reserved
1. To activate the curve-fitting
tools, select Tools : Basic Fitting
from the menu bar in the figure.
2. The basic fitting window opens
on top of the plot.
3. By checking linear, cubic, and
show equations, the plot is
generated.
Basic Fitting Tools
Copyright © TELCOMA. All Rights Reserved
To open the curve-fitting
toolbox, type cftool in the command
window.
Curve Fitting Toolbox
Copyright © TELCOMA. All Rights Reserved
1. A string in MATLAB consists of any number of characters and is contained in a single quotes.
2. Strings are vectors in which every element is a single character.3. MATLAB also has built-in functions that are written specifically to
manipulate strings.
Introduction
Copyright © TELCOMA. All Rights Reserved
1. A string consists of any number of characters (including, possibly, none). The following are examples of strings:
' ''X''Cat''Hello there''123'
2. A substring is a subset or part of a string. For example, ‘there’ is a substring within the string ‘Hello there’.
Creating String Variables...
Copyright © TELCOMA. All Rights Reserved
3. Characters include letters of the alphabet, digits, punctuation marks, white space, and control characters.
4. Control characters are characters that cannot be printed, but accomplish a task.
5. White space characters include the space, tab, newline, and carriage return.
6. Leading blanks are blank spaces at the beginning of a string.7. Trailing blanks are blank spaces at the end of a string.
Creating String Variables...
Copyright © TELCOMA. All Rights Reserved
8. There are several ways that string variables can be created.
9. By using an assignment statement.
10. By using ‘input’ function.
Creating String Variables
Copyright © TELCOMA. All Rights Reserved
1. Strings are treated as vectors of characters.
2. The number of characters in a string can be found by using the length function.
Strings as Vectors...
Copyright © TELCOMA. All Rights Reserved
3. Expressions can refer to an individual element (a character within the string), or a subset of a string, or a transpose of a string.
4. A blank space in a string is a valid character within the string.
Strings as Vectors...
Copyright © TELCOMA. All Rights Reserved
5. A character matrix can be created that consists of strings in every row.
6. The following is created as a column vector of strings, but the end result is that it is a matrix in which every element is a character.
Strings as Vectors...
Copyright © TELCOMA. All Rights Reserved
7. With a character matrix one can refer to an individual element (a single character) or an individual row (one of the strings).
8. As rows within a matrix must always be the same length, the shorter strings must be padded with blanks so that all strings have the same length; otherwise, an error will occur.
Strings as Vectors
Copyright © TELCOMA. All Rights Reserved
1. It means to join strings together. 2. Note that the variable names (or
strings) must be separated by a blank space in the brackets, but there is no space in between the strings when they are concatenated.
Concatenation...
Copyright © TELCOMA. All Rights Reserved
3. The method of using the square brackets will concatenate all of the characters in the strings, including all leading and trailing blanks.
4. The strcat function, however, will remove trailing blanks (but not leading blanks) from strings before concatenating.
Concatenation
Copyright © TELCOMA. All Rights Reserved
1. The blanks function will create a string consisting of n blank characters.
2. It is usually most useful to use this function when a number of blank spaces is desired in between.
Customizing String...
Copyright © TELCOMA. All Rights Reserved
3. The sprintf function will create a string in which the output is not suppressed so the value of the string variable is shown.
Customizing String
Copyright © TELCOMA. All Rights Reserved
1. The deblank function will remove blank spaces (only trailing blanks) from the end of a string.
Removing White Space Characters...
Copyright © TELCOMA. All Rights Reserved
2. The strtrim function will remove both leading and trailing blanks from a string, but not blanks in the middle of the string.
Removing White Space Characters
Copyright © TELCOMA. All Rights Reserved
MATLAB has two functions that convert strings to all uppercase letters, or lowercase, called upper and lower.
Changing Case
Copyright © TELCOMA. All Rights Reserved
1. The function strcmp compares strings, character by character.
2. Note that for strings these functions are used to determine whether strings are equal to each other or not, not the equality operator ==.
Comparing String...
Copyright © TELCOMA. All Rights Reserved
3. The function strncmp compares only the first n characters in strings and ignores the rest.
4. The first two arguments are the strings to compare, and the third argument is the number of characters to compare (the value of n).
Comparing String
Copyright © TELCOMA. All Rights Reserved
1. The function strfind receives two strings as input arguments.
2. The general form is
strfind(string, substring)
3. If there are no occurrences, the empty vector is returned.
Finding Strings
Copyright © TELCOMA. All Rights Reserved
1. The function strrep finds all occurrences of a substring within a string and replaces them with a new substring.
2. The format is:
strrep(string, oldsubstring, newsubstring)
Replacing Strings
Copyright © TELCOMA. All Rights Reserved
1. The strtok function breaks a string into two pieces.
2. The format is:
[token, rest] = strtok(string)
3. Alternate delimiters can be defined. The format
[token, rest] = strtok(string, delimeters)
Separating Strings
Copyright © TELCOMA. All Rights Reserved
The function eval is used to evaluate a string.
Evaluating a String...
Copyright © TELCOMA. All Rights Reserved
1. The function “isspace” returns logical true for every character that is a whitespace character.
2. The “ischar” function will return logical true if the vector argument is a character vector, or logical false if not.
The “is” Function
Copyright © TELCOMA. All Rights Reserved
1. To convert numbers to strings there are two functions int2str for integers and num2str for real numbers (which also works with integers).
Conversion between String and Number...
Copyright © TELCOMA. All Rights Reserved
2. The function str2num does the reverse; it takes a string in which a number is stored and converts it to the type double.
Conversion between String and Number
Copyright © TELCOMA. All Rights Reserved
1. The sscanf function reads data from a string.2. The strjust function justifies a string.3. The mat2str function converts a matrix to a string.4. The isstrprop function examines string properties.
Other Features
Copyright © TELCOMA. All Rights Reserved
1. Data structures are variables that store more than one value.2. An array is a data structure in which all of the values are logically
related.3. A cell array is a kind of data structure that stores values of different
types.4. Cell arrays can be vectors or matrices; the different values are referred
to as the elements of the array.5. Structures are data structures that group together values that are
logically related, but are not the same thing and not necessarily the same type.
Introduction
Copyright © TELCOMA. All Rights Reserved
1. To create cell arrays curly braces are used instead of square brackets.
2. To create a row vector cell array, the values are separated by commas.
3. To create a column vector cell array, the values are instead separated by semicolons.
Creating cell arrays...
Copyright © TELCOMA. All Rights Reserved
4. The type of cell arrays is cell.5. Another method of creating a
cell array is to simply assign values to specific array elements and build it up element by element.
Creating cell arrays
Copyright © TELCOMA. All Rights Reserved
1. Using curly braces for the subscripts will reference the contents of a cell; called content indexing.
Referring to and display elements...
Copyright © TELCOMA. All Rights Reserved
2. Using parentheses for the subscripts references the cells; this is called cell indexing.
Referring to and display elements...
Copyright © TELCOMA. All Rights Reserved
3. The celldisp function displays the contents of all elements of the cell array.
Referring to and display elements...
Copyright © TELCOMA. All Rights Reserved
4. To delete an element from a vector cell array or to delete an entire row or column, cell indexing is used.
Referring to and display elements
Copyright © TELCOMA. All Rights Reserved
1. As cell arrays can store different types of values, strings of different lengths can be stored in the elements.
2. The length of each string can be displayed using a for loop to loop through the elements of the cell array.
Storing strings in cell arrays...
Copyright © TELCOMA. All Rights Reserved
3. The function cellstr converts from a character array padded with blanks to a cell array in which the trailing blanks have been removed.
Storing strings in cell arrays...
Copyright © TELCOMA. All Rights Reserved
4. The char function can convert from a cell array to a character matrix.
5. The function iscellstr will return logical true if a cell array is a cell array of all strings or logical false if not.
Storing strings in cell arrays
Copyright © TELCOMA. All Rights Reserved
1. Creating structure variables can be accomplished by using the struct function.
Create and Modify Structure Variables...
Copyright © TELCOMA. All Rights Reserved
2. An alternative method of creating structures is by using the dot operator to refer to the fields within the structure.
Create and Modify Structure Variables...
Copyright © TELCOMA. All Rights Reserved
3. The disp function will display either the entire structure or an individual field.
4. By using fprintf, only individual fields can be printed.
Create and Modify Structure Variables...
Copyright © TELCOMA. All Rights Reserved
5. The function rmfield removes a field from a structure.
Create and Modify Structure Variables
Copyright © TELCOMA. All Rights Reserved
1. The function isstruct will return logical 1 for true if the variable argument is a structure variable or 0 if not.
2. The isfield function returns logical true if a field name is a field in the structure argument or logical false if not.
Related structure functions...
Copyright © TELCOMA. All Rights Reserved
3. The fieldnames function will return the names of the fields that are contained in a structure variable.
Related structure functions
Copyright © TELCOMA. All Rights Reserved
1. In many applications, including database applications, information would normally be stored in a vector of structures, rather than in individual structure variables.
Vectors of Structures...
Copyright © TELCOMA. All Rights Reserved
2. For loop can also be used to display each element in the packages vector.
Vectors of Structures
Copyright © TELCOMA. All Rights Reserved
1. To get started, select the guide icon from the toolbar, or type guide at the
command line.
2. The GUIDE Quick Start window will open.
3. To start a new project, simply select the Blank GUI template, located in the
list on the left-hand side of the window.
4. After that a new figure window—called the GUIDE layout editor—will open,
Creating a layout...
Copyright © TELCOMA. All Rights Reserved
5. To create a layout of buttons,
textboxes, and graphics
windows, use the icons on the
left-hand side of the window in
the “component palette.”
Creating a Layout...
Copyright © TELCOMA. All Rights Reserved
6. To change the palette of tools
to a list of the item names
select
File ➞ Preferences ➞ GUIDE
then check “Show names in
component palette.”
Creating a Layout...
Copyright © TELCOMA. All Rights Reserved
7. The Property Inspector is used
to modify the design
elements.
8. The Property Inspector can be
accessed from the menu bar
by selecting
View ➞ Property Inspector
Creating a Layout...
Copyright © TELCOMA. All Rights Reserved
9. The Property Inspector lists a
wide range of properties for
the selected object in the
GUIDE window.
10. One can change the font of
the message displayed,
change the color of the text
box etc.
Creating a Layout...
Copyright © TELCOMA. All Rights Reserved
11. Use the same process to
modify the properties of the
“edit text” box.
12. The GUIDE window can be
saved and run by selecting
the Save and Run icon from
the window toolbar.
Creating a Layout
Copyright © TELCOMA. All Rights Reserved
1. The m-file is organized as a function, with multiple sub-functions.
2. Some of the subfunctions create the graphics in the saved window.
3. Others are reserved for adding the code that will cause an action when
a user interacts with the GUI.
4. To see a list of the functions in the saved file, select the Show Functions
icon on the toolbar.
Adding Code to M-File...
Copyright © TELCOMA. All Rights Reserved
5. The only functions a user should modify are labeled as:
gui_name_OpeningFcn
graphics_object_name_Callback
Adding Code to M-File
Copyright © TELCOMA. All Rights Reserved
1. It allows the user to interact with the GUI.
2. Clicking on the function of interest will shows the corresponding
section of code.
3. An alternative approach to find the appropriate sub-function to
modify is to use the layout editor.
4. Right click on the graphics object, select View Callbacks, then
select Callback.
Callbacks
Copyright © TELCOMA. All Rights Reserved
1. When a user types in a textbox, the contents are stored as the
string property.
2. To retrieve the information and use it in m-file, use the get
function.
get Function
Copyright © TELCOMA. All Rights Reserved
1. To run GUI, select the Save and
Run icon from the m-file window
or from the Guide layout editor.
2. To run the GUI, type a value into
the edit window, and hit enter.
Run GUI...
Copyright © TELCOMA. All Rights Reserved
3. The opening function is the only
other sub-function to be
modified in this file.
4. It executes when the GUI first
runs, and can be used to control
how the figure window appears
before the user starts adding
data.
Run GUI
Copyright © TELCOMA. All Rights Reserved
1. It is an interactive, graphics-based program that allows you to
solve problems by creating models using a set of built-in
“blocks.”
2. It is part of the MATLAB software suite, and requires MATLAB to
run.
Introduction
Copyright © TELCOMA. All Rights Reserved
1. Designed to provide a convenient method for analyzing dynamic
systems, i.e., systems that change with time.
2. It found early acceptance in the signal processing community, and is
reminiscent of the approach used to program analog computers .
3. One way to think of Simulink is as a virtual analog computer.
4. Its strength is its ability to model dynamic systems—which are
modeled mathematically as differential equations .
Applications
Copyright © TELCOMA. All Rights Reserved
To start Simulink, open MATLAB
and type simulink into the command
window or select the Simulink icon
from the Shortcut toolbar
Getting Started...
Copyright © TELCOMA. All Rights Reserved
The Simulink Library Browser
opens, showing the available
libraries of blocks used to create a
Simulink model.
To view the blocks, either select
the library from the left-hand pane
or double click on the icons in the
right-hand pane.
Getting Started...
Copyright © TELCOMA. All Rights Reserved
To create a new model, select
File ➞ New ➞ Model
from the browser window.
Getting Started...
Copyright © TELCOMA. All Rights Reserved
First model will simply add two
numbers.
From the library, click and drag
the constant block into the model
window.
Repeat the process, so that
there are two copies of constant
block in the model.
Model 1
Copyright © TELCOMA. All Rights Reserved
Now drag the sum block into
the model.
Draw connections between the
constants and sum block by clicking
and dragging between the ports.
To add a display, select and
drag display block to model and
connect it to output port of sum
block.
Model 1
Copyright © TELCOMA. All Rights Reserved
The last thing we need to do
before running the model is to
adjust the simulation time, from the
box on the menu bar.
Run the simulation by selecting
the run button on the toolbar or by
selecting Simulation ➞ Start from
the menu bar.
Model 1
Copyright © TELCOMA. All Rights Reserved
Save this model in the usual
way, by selecting File ➞ Save and
adding an appropriate name.
The files are stored with the
extension, .mdl.
Model 1
Copyright © TELCOMA. All Rights Reserved
To solve differential equations with Simulink, create a model by dragging
the appropriate blocks onto the model window, and connect them.
The blocks include; a clock, to generate times (Source library), a math
function block, modified in the parameter window to square the block
input (Math Operations library), a sum block (Commonly Used Blocks library),
an integrator block (Continuous library), and a scope block (Sink library).
Model 2