You are on page 1of 190

Summer Workshop on

MATLAB for Engineering Students

Instructor: Ravi Kiran Maddali, Department of Mathematics

| 18-22 May, 2014| © 2014 UPES


DAY I: Lecture 1

Introduction to MATLAB

18-22 May, 2014 © 2014 UPES


INTRODUCTION TO MATLAB

18-22 May, 2014 © 2014 UPES


1.1 WHAT IS MATLAB
 MATLAB is a software package for high performance
numerical computation and visualization developed by
MathWorks (An American company that specializes in
Mathematical Computing Software).
 It provides an interactive environment with hundreds of built-in
functions for technical computation, graphics and animations.
 It has its own high level programming language.
 Applications of MATLAB include math and computation,
algorithm development, data acquisition, modeling and
simulation, data analysis and visualization, scientific and
engineering graphics, application development including GUI
(Graphical User Interface).
 MATLAB stands for ‘Matrix Laboratory’.
18-22 May, 2014 © 2014 UPES
1.2 Features of MATLAB

18-22 May, 2014 © 2014 UPES


1.2 Features of MATLAB (contd…)
 MATLAB’s built-in functions provide excellent tools for linear algebra
computations, data analysis, signal processing, optimization,
numerical solution of ODEs, quadrature and many other scientific
computations.
 There are numerous functions for 2D and 3D graphics.
 For those who cannot do without their FORTRAN or C codes,
MATLAB provides an external interface to run those programs from
within MATLAB.
 The MATLAB is not limited to the built-in functions. We can create his
own functions using MATLAB language. Once written, these user
defined functions behave as built-in functions.
 MATLAB’s programming language is easy to learn and use.
 MATLAB comes with toolboxes which are collection of functions
written for special applications such as symbolic computation, image
processing, signal processing, statistics, control system design, neural
networks etc.
18-22 May, 2014 © 2014 UPES
1.3 Basic Building Block of MATLAB
 The basic building block of MATLAB is the MATRIX.
 The fundamental data type is array and we need not declare
the dimensions of a matrix while declaring the variables.
 Vectors, scalars, real and complex matrices are all
automatically handled as special cases of the basic data
type.
 The built-in functions are optimized for vector operations
 Vectorization refers to a manner of computation in which an
operation is performed simultaneously on a list of numbers (a
vector) rather than sequentially on each member of the list.
 Vectorized commands and codes run much faster in
MATLAB.
18-22 May, 2014 © 2014 UPES
1.4 Symbolic Computations
 Symbolic algebra means that the computation is done in
terms of symbols or variables rather than on numbers. For
example if you type (x+y)^2 on your computer and the
computer responds by saying that the expression is equal to
𝑥 2 + 2𝑥𝑦 + 𝑦 2 , then your computer does symbolic algebra.
 Software packages that do symbolic algebra are known as
Computer Algebra Systems.
 MATLAB is primarily a numerical computational package,
although with the Symbolic toolbox it can do symbolic
algebra. The software systems like MATHEMATICA and
MAPLE are primarily symbolic algebra systems.
 MATHEMATICA and MAPLE also do numerical
computations.
18-22 May, 2014 © 2014 UPES
1.4 Why Learn MATLAB?(MATLAB Vs Mathematica, Maple)
 MATLAB’s ease of use is the best feature. It has a shallow
learning curve (more learning with less effort) while the
computer algebra systems have a steep learning curve(more
effort).
 MATLAB is more faster than any other package or language
in numerical computations. In numerical computations
especially those that utilize vectors and matrices, MATLAB
beats every other language/software in terms of ease of use,
availability of built-in functions, ease of programming, and
speed.
 The proof for the above point is the phenomenal growth of
MATLAB users around the world. There are more than 2500
universities and thousands of companies listed as registered
users. MATLAB’s popularity made Mathematica to provide
extensions for files in MATLAB format.
18-22 May, 2014 © 2014 UPES
1.5 The MATLAB system
The MATLAB System consists of
 Development Environment
 The MATLAB Mathematical Function Library
 The MATLAB Language
 Graphics
 The MATLAB Application Program Interface (API)

18-22 May, 2014 © 2014 UPES


1.5 MATLAB system contd…
 Development Environment is the set of tools that helps us
to use MATLAB functions and files. Many of these tools are
GUIs. It includes MATLAB desktop, command window,
command history, editor and debugger, workspace, search
path.
 MATLAB function library is the vast collection of
computational algorithms ranging from elementary functions
like sum, cosine, sine, to more sophisticated functions like
Bessel functions and Fast Fourier transformations.
 MATLAB language is the high level matrix language with
control flow statements, functions, data structures,
input/output , and object oriented programming features. It
allows us to make simple programs as well as to create a
large complex application programs.

18-22 May, 2014 © 2014 UPES


1.5 MATLAB system contd…
 Graphics include high level functions for two dimensional
and three dimensional data visualization, image processing,
animation.
 The MATLAB API is a library that allows us to write C or
FORTRAN programs that interact with MATLAB. It also
include provision to call routines from MATLAB, known as
Dynamic Linking.

18-22 May, 2014 © 2014 UPES


1.6 The MATLAB desktop

18-22 May, 2014 © 2014 UPES


1.6 The MATLAB desktop Contd…
 It contains tools (GUIs) for managing files, Variables and
applications associated with MATLAB.
 The general desktop tools are: command window,
command history, launch pad, help browser, current
directory browser, workspace browser, array editor,
editor/debugger.

18-22 May, 2014 © 2014 UPES


1.6.1 The command window is used to enter variables and
run functions and M-files.

18-22 May, 2014 © 2014 UPES


1.6.2 The Command History contains all the commands you
enter in the command window. You can view and reuse these
commands.

18-22 May, 2014 © 2014 UPES


1.6.3 The Current Directory Browser
 MATLAB file operations use the current directory and the
search path as reference points.
The Search Path
 MATLAB uses search path to determine how to execute
functions you call. It uses search path to find M-files and other
related files.
 To see the search path or to edit the search path use Set
Path command from File menu.
 Any file you want to run must either be in the current director
or on the search path.

18-22 May, 2014 © 2014 UPES


1.6.4 The Workspace Browser

 The MATLAB workspace consists of the set of variables built


up during a MATLAB session and stored in memory.
 We can add variables to the workspace by using functions,
running M-files, and also by loading saved workspaces.
 To use the workspace and information about each variable,
use the workspace browser, or use the functions who and
whos.
 To delete variables from the workspace, select the variable
and select delete from the Edit menu.
 The above task can be achieved by using clear function.

18-22 May, 2014 © 2014 UPES


1.6.4 The Workspace Browser (contd…)

 The workspace is volatile i.e., it will not be maintained once we


end the MATLAB session.
 We can also save the workspace to a file that can be read during
a later sessions by Save Workspace As option from the File
menu, which is saved as MAT-file with .mat extension.
 To load a .mat file use Import Data from File menu or
alternatively use Load function.
The Array Editor
 Double click on a variable in the Workspace browser to see it in
the Array Editor to view and edit values in the variables.

18-22 May, 2014 © 2014 UPES


1.6.5 Editor/Debugger

 Use the Editor/Debugger to create and debug M-files, which


are programs we write to run MATLAB functions.
 The Editor/Debugger provides a graphical user interface for
basic text editing, as well as for M-file debugging.
 If you need to view the contents of M-file in command
window, use the type function.

18-22 May, 2014 © 2014 UPES


1.7 Input/Output

 Data Type: The fundamental data type is ‘array’. It


encompasses several distinct data types such as integers,
doubles, matrices, character strings, and structures.
 Dimensioning: Dimensioning is automatic. No dimensioning
statements are required. You can find the dimensions of an
existing vector/matrix by size and length commands.
 Case Sensitivity: MATLAB is case senstitive. Thus a and A
are different variables.

18-22 May, 2014 © 2014 UPES


1.8 The Output format
 Though computations inside MATLAB are performed using
double precision, the appearance of floating point numbers on
the screen is controlled by the output format in use. The
following table shows the printed value of 10𝜋 in 9 different
formats:
format short 31.4159
format short e 3.1416e+001
format long 31.41592653589793
format long e 3.141592653589793e+001
format short g 31.416
format long g 31.4159265358979
format hex 403f6a7a2955385e
format rat 3550/113
format bank 31.42
18-22 May, 2014 © 2014 UPES
1.9 File Types in MATLAB
MATLAB has 3 types of files for storing information
 M-files: are standard ASCII text files, with an extension .m to
the file name. There are two types of files. Script files and
function files. Most of the programs we write in MATLAB are
stored as M-files. All built-in functions are also M-files.
 Mat-files: are binary data files, with a .mat extension. Mat files
are created by MATLAB when you save data with the save
command. The data is written in special format that only
MATLAB can understand. Mat files are loaded into MATLAB
by load command.
 Mex-files: are MATLAB callable Fortran or C programs with
.mex extension to the filename. But these require lot of
patience and experience to work.
18-22 May, 2014 © 2014 UPES
1.10 General Commands to remember
 On-line help
help lists topics on which help is available
helpwin opens the interactive help window
helpdesk opens the web browser based help facility
help topic provides help on topic
lookfor string lists help topics containing string
demo runs the demo program

18-22 May, 2014 © 2014 UPES


1.10 General Commands to remember (contd…)
 Workspace information
who lists variables currently in the workspace
whos lists variables currently in the workspace with their size
what lists m-, mat-, and mex-files on the disk
clear clears the workspace, all variables are removed
clear x y z clears only variables x, y and z
clear all clears all variables and functions from workspace
mlock fun locks function fun so that clear cannot remove it
munlock fun unlocks function fun so that clear can remove it
clc clears command window, command history is lost
home same as clc
clf clears figure window

18-22 May, 2014 © 2014 UPES


1.10 General Commands to remember (contd…)
 Directory information
pwd shows the current working directory
cd changes the current working directory
dir lists contents of the current directory
ls lists contents of the current directory, same as dir
path gets or sets MATLAB search path
editpath modifies MATLAB search path
copyfile copies a file
mkdir creates a directory

18-22 May, 2014 © 2014 UPES


1.10 General Commands to remember (contd…)
 Most general commands
pwd shows the current working directory
cd changes the current working directory
dir lists contents of the current directory
ls lists contents of the current directory, same as dir
path gets or sets MATLAB search path
editpath modifies MATLAB search path
copyfile copies a file
mkdir creates a directory

18-22 May, 2014 © 2014 UPES


1.10 General Commands to remember (contd…)
computer tells you the computer type you are using
clock gives you wall clock time and date as a vector
date tells you the date as a string
more controls the paged output according to the
screen size
ver gives the license and the version information
about MATLAB installed on your computer
^c (Control-c) local abort, kills the current command
execution
quit quits MATLAB
exit same as quit
18-22 May, 2014 © 2014 UPES
Questions ???

18-22 May, 2014 © 2014 UPES


DAY I: Lecture 2

Understanding Command Window


&
Working with Arrays

18-22 May, 2014 © 2014 UPES


2.1 Entering Commands in Command Window

 We should enter commands at the command prompt


>>.
 MATLAB retains your previous keystrokes.
 Use up-arrow to scroll back through the commands.
 Press the key once to see the previous entry, and so
on.
 Use the down-arrow to scroll forward. Edit a line using
the left- and right arrow keys, the backspace key and
the delete key.
 Press the enter key to execute the command.
18-22 May, 2014 © 2014 UPES
2.2 Scalar Arithmetic Operations

18-22 May, 2014 © 2014 UPES


2.2 Scalar Arithmetic Operations (contd…)

An Example Session

>> 8/10
ans=
0.8000
>> 5*ans
ans=
4
>> r=8/10
ans=
0.8000
>>r
r=
0.8000
18-22 May, 2014 © 2014 UPES
2.3 Order of Precedence

18-22 May, 2014 © 2014 UPES


2.3.1 Examples of Precedence (contd…)
>> 8 + 3*5
ans= To avoid mistakes, feel free to insert
parentheses wherever you are
23 unsure of the effect precedence will
>> (8+3)*5 have on the calculation. Use of
ans= parentheses also improves the
readability of your MATLAB
55 expressions.
>> 4^2-12-8/4*2
ans=
0
>> 4^2-12-8/(4*2)
ans=
3
>> 27^(1/3)+32^(0.2)
ans=
5
18-22 May, 2014 © 2014 UPES
2.3.2 The Assignment Operator =
 Typing x = 3 assigns the value 3 to the variable x.

 We can then type x = x + 2. This assigns the value 3 + 2 = 5


to x.

 In algebra we can write x + 2 = 20, but in MATLAB cannot.

 In MATLAB the left side of the = operator must be a single


variable.

 The right side must be a computable value.

18-22 May, 2014 © 2014 UPES


2.4 Special Variables and Constants

18-22 May, 2014 © 2014 UPES


2.5 Complex Number Operations
The number c1 = 1 – 2i is entered as follows:
>>c1 = 1-2i.
*An asterisk is not needed between i or j and a number,
although it is required with a variable, such as c2 = 5 - i*c1.
* Be careful. The expressions
y = 7/2*i
and
x = 7/2i
give two different results:
y = (7/2)i = 3.5i
and
x = 7/(2i) = –3.5i.

18-22 May, 2014 © 2014 UPES


2.5 Complex Number Operations (contd…)
Addition, Subtraction, Multiplications and Division of
complex numbers are easily done.

>> s=3+7i;w=5-9i;

>>w+s gives 8.0000-2.0000i

>>w*s gives 78.0000+8.0000i

>>w/s gives -0.8276-1.0690i

18-22 May, 2014 © 2014 UPES


2.6 Basic Mathematical Functions

18-22 May, 2014 © 2014 UPES


2.7 Naming Variables in MATLAB

 The term workspace refers to the names and values


of any variable in use in the current work session.
 Variable names must begin with a letter; the rest of
the name can contain letters, digits, and underscore
characters.
 MATLAB is case sensitive.
 The following names represent five different variables:
speed, Speed, SPEED, Speed_1 and Speed_2.
 MATLAB variables can be no longer than 63
characters.
18-22 May, 2014 © 2014 UPES
2.8 Creating and working with numeric arrays
Row vectors: To create a row vector, separate the elements by
space or comma. Use square brackets. For example,
>>p=[3,7,9] or p=[3 7 9]
Output: p=3 7 9
Column vectors: To create a column vector, separate the elements
by semicolon. Use square brackets. For example,
>>p=[3;7;9] or p=[3 7 9]’ (Transpose notation)
Output:
p=
3
7
9
18-22 May, 2014 © 2014 UPES
2.9 Appending Vectors
 You can create vectors by ''appending'' one vector to another.
 For example, to create the row vector u whose first three
columns contain the values of r = [2,4,20] and whose
fourth, fifth, and sixth columns contain the values of
w = [9,-6,3], you type u = [r,w]. The result is the
vector u = [2,4,20,9,-6,3].
 2.10 Entering Matrices
>> A=[1 2 3;4 5 6;7 8 9]
A=
123
456
789
18-22 May, 2014 © 2014 UPES
2.10 Element by Element operations

.* term by term multiplications


./ term by term division
.^ term by term exponentiation
Example: Equation of a straight line: The equation of a straight
line is y = mx+c, where m and c are constants. Compute the y-
coordinates of a line with slope m = 0.5 and the intercept c = −2
at the following x-coordinates: x = 0, 1.5, 3, 4, 5, 7, 9, and 10.
>>x=[0 1.5 3 4 5 7 9 1 0];y = 0.5*x-2;
Solution:
y = [−2.0000 −1.2500 −0.5000 0 0.5000 1.5000 2.5000 3.0000].
18-22 May, 2014 © 2014 UPES
2.11 Examples of Vector operations

18-22 May, 2014 © 2014 UPES


2.12 Save, Load and xlsread commands

Save – to save the workspace


variables
Load – To load the variables into
workspace
xlsread – to import data from excel

18-22 May, 2014 © 2014 UPES


Questions ???

18-22 May, 2014 © 2014 UPES


DAY I: Lecture 3

Creating Simple Plots in MATLAB

18-22 May, 2014 © 2014 UPES


3.1 The basic PLOT commands:

In this topic, we discuss

 The plot command


 The fplot commnad
 Plotting multiple graphs in same plot
 Formatting plots

18-22 May, 2014 © 2014 UPES


3.2 Overview of a 2 D plot:

18-22 May, 2014 © 2014 UPES


3.3 The two dimensional plot ( ) command:

The syntax is plot(x,y) where x and y are one dimensional


vectors. It is mandatory that both x and y are of same length.

 The plot command creates a single curve with the x values on


the abscissa (horizontal axis) and the y values on the ordinate
(vertical axis).

 The curve is made from segments of lines that connect the


points that are defined by the x and y coordinates of the
elements in the two vectors.

18-22 May, 2014 © 2014 UPES


3.3.1 Creating the X and Y vectors:

 If data is given, the information is entered as the elements of


the vectors x and y.

 If the values of y are determined by a function from the values


of x, than a vector x is created first, and then the values of y
are calculated for each value of x. The spacing (difference)
between the elements of x must be such that the plotted curve
will show the details of the function.

18-22 May, 2014 © 2014 UPES


3.3.2 Plot of Given Data:
If the given data is:

x 1 2 3 5 7 7.5 8 10

y 2 6.5 7 7 5.5 4 6 8

A plot can be created by the commands shown below.


This can be done in the Command Window, or by writing
and then running a script file.
>> x=[1 2 3 5 7 7.5 8 10];
>> y=[2 6.5 7 7 5.5 4 6 8];
>> plot(x,y)

Once the plot command is executed, the Figure Window


opens with the following plot.
18-22 May, 2014 © 2014 UPES
3.3.2 Plot of Given Data (contd…):

18-22 May, 2014 © 2014 UPES


3.4 Line Specifiers in the plot( ) command
Line specifiers can be added in the plot command to:

 Specify the style of the line.


 Specify the color of the line.
 Specify the type of the markers (if markers are
desired).

plot(x,y,‘line specifiers’)

18-22 May, 2014 © 2014 UPES


3.4.1 Line Specifiers in the plot( ) command

plot(x,y,‘line specifiers’)

Line Specifier Line Specifier Marker Specifier


Style Color Type

Solid - red r plus sign +


dotted : green g circle o
dashed -- blue b asterisk *
dash-dot -. Cyan c point .
magenta m square s
yellow y diamond d
black k

18-22 May, 2014 © 2014 UPES


3.4.2 Line Specifiers in the plot( ) examples

 The specifiers are typed inside the plot() command as strings.


 Within the string the specifiers can be typed in any order.
 The specifiers are optional. This means that none, one, two, or
all the three can be included in a command.
Examples
plot(x,y) A solid blue line connects the points with no markers.

plot(x,y,’r’) A solid red line connects the points with no markers.

plot(x,y,’--y’) A yellow dashed line connects the points.

plot(x,y,’*’) The points are marked with * (no line between the
points.)

plot(x,y,’g:d’) A green dotted line connects the points which are


marked with diamond markers.
18-22 May, 2014 © 2014 UPES
3.4.3 PLOT OF GIVEN DATA USING LINE SPECIFIERS IN
THE plot() COMMAND

Year 1988 1989 1990 1991 1992 1993 1994

Sales (M) 127 130 136 145 158 178 211

>> year = [1988:1:1994];


>> sales = [127, 130, 136, 145, 158, 178, 211];
>> plot(year,sales,'--r*')

18-22 May, 2014 © 2014 UPES


3.4.3 Plot of previous command:

18-22 May, 2014 © 2014 UPES


3.5 The fplot () command:
Thefplot command can be used to plot a function with the form:
y = f(x)

fplot(‘function’,limits)

 The function is typed in as a string.

 The limits is a vector with the domain of x, and optionally with limits
of the y axis:

[xmin,xmax] or [xmin,xmax,ymin,ymax]
 Line specifiers can be added.

18-22 May, 2014 © 2014 UPES


3.5.1 Example of fplot() command:
A plot of: y  x 2  4 sin( 2 x)  1 for 3 x  3

>> fplot('x^2 + 4 * sin(2*x) - 1', [-3 3])

18-22 May, 2014 © 2014 UPES


3.6 The hold on command:
The hold on is used to plot multiple commands on the
same figure window

Example:
>> t=0:.1:10
>>plot(t,sin(t));
>>hold on;
>>plot(t,cos(t));

18-22 May, 2014 © 2014 UPES


3.6 The hold on command Contd…:

hold on Holds the current plot and all axis properties


so that subsequent plot commands add to the
existing plot.

hold off Returns to the default mode whereby plot


commands erase the previous plots and reset
all axis properties before drawing new plots.

This method is useful when all the information (vectors)


used for the plotting is not available at the same time.

18-22 May, 2014 © 2014 UPES


3.6 The hold on command Contd…:

Plot of the function, y  3x3  26 x  10 and its first and second


derivatives, for
 2  x  4 all in the same plot.
x = [-2:0.01:4];
y = 3*x.^3-26*x+6;
yd = 9*x.^2-26;
ydd = 18*x;
plot(x,y,'-b')
hold on First graph is created.

plot(x,yd,'--r')
plot(x,ydd,':k') Two more graphs are created.
hold off

18-22 May, 2014 © 2014 UPES


3.6 The hold on command contd..:
The output of the previous commands

18-22 May, 2014 © 2014 UPES


3.7 Plotting multiple graphs using plot() command

Plot of the function, y  3x3  26 x  10 and its first and second


derivatives, for
 2  x , 4 all in the same plot.
x = [-2:0.01:4]; vector x with the domain of the function.
y = 3*x.^3-26*x+6; Vector y with the function value at each x.
yd = 9*x.^2-26;
Vector yd with values of the first derivative.
ydd = 18*x;
Vector ydd with values of the second derivative.
plot(x,y,'-b',x,yd,'--r',x,ydd,':k')

Create three graphs, y vs. x (solid blue line), yd


vs. x (dashed red line), and ydd vs. x (dotted
black line) in the same figure.
18-22 May, 2014 © 2014 UPES
3.7 The Previous Commands output

18-22 May, 2014 © 2014 UPES


3.8 Formatting Plots

A plot can be formatted to have a required appearance.

With formatting we can:

 Add title to the plot.


 Add labels to axes.
 Change range of the axes.
 Add legend.
 Add text blocks.
 Add grid.

18-22 May, 2014 © 2014 UPES


3.8 Formatting Plots contd…
There are two methods to format a plot:

1. Formatting commands.
In this method commands, that make changes or
additions to the plot, are entered after the plot()
command. This can be done in the Command
Window, or as part of a program in a script file.

2. Formatting the plot interactively in the Figure Window.


In this method the plot is formatted by clicking on the
plot and using the menu to make changes or add
details.
18-22 May, 2014 © 2014 UPES
3.9 The Formatting commands

title(‘string’)
Adds the string as a title at the top of the plot.

xlabel(‘string’)
Adds the string as a label to the x-axis.

ylabel(‘string’)
Adds the string as a label to the y-axis.

axis([xmin xmax ymin ymax])


Sets the minimum and maximum limits of the x- and y-axes.

18-22 May, 2014 © 2014 UPES


3.9 The Formatting commands contd…
legend(‘string1’,’string2’,’string3’)
Creates a legend using the strings to label various curves (when
several curves are in one plot). The location of the legend is
specified by the mouse.

text(x,y,’string’)
Places the string (text) on the plot at coordinate x,y relative to
the plot axes.

gtext(‘string’)
Places the string (text) on the plot. When the command
executes the figure window pops and the text location is clicked
with the mouse.

18-22 May, 2014 © 2014 UPES


3.10 Example of the Formatting commands

Commands to plot a graph

x=[10:0.1:22]; Creating vector x for plotting the theoretical curve.

y=95000./x.^2; Creating vector y for plotting the theoretical curve.

xd=[10:2:22]; Creating a vector with coordinates of data points.


yd=[950 640 460 340 250 180 140]; Creating a vector with light
intensity from data.
plot(x,y,'-','LineWidth',1.0)
hold on
plot(xd,yd,'ro--','linewidth',1.0,'markersize',10)
hold off

18-22 May, 2014 © 2014 UPES


3.10 Example of the Formatting commands contd..

The formatting commands for the previous plot are


xlabel('DISTANCE (cm)')
Labels for the axes.
ylabel('INTENSITY (lux)')
Title for the plot.
title('\fontname{Arial}Light Intensity as a Function of Distance','FontSize',14)
axis([8 24 0 1200])
text(14,700,'Comparison between theory and
Setting limits of the axes.
experiment.','EdgeColor','r','LineWidth',2)
legend('Theory','Experiment',0) Creating a legend.

Creating a legend.

The plot that is obtained is shown again in the next slide.

18-22 May, 2014 © 2014 UPES


3.10 The formatted plot is

18-22 May, 2014 © 2014 UPES


Questions ???

18-22 May, 2014 © 2014 UPES


DAY I: Lecture 4

Working with Script files

18-22 May, 2014 © 2014 UPES


4.1 Script Files in MATLAB
Operations in MATLAB can be performed in two ways:
 In the interactive mode, in which all commands are entered
directly in the command window
 By running a MATLAB program stored in script file. This type of
file contains MATLAB commands, so running it is equivalent to
typing all the commands-one at a time-at the command window.
You can run the file by typing its name at the command window
prompt.
 So, a script file is a user created file with a sequence of MATLAB
commands in it. The file must be saved with .m extension, thereby
making it an M-file.

18-22 May, 2014 © 2014 UPES


4.2 comment in MATLAB
The symbol % designates a comment, which is not executed by
MATLAB. Comments are used mainly in script files for the
purpose of documenting the file. The comment symbol may be put
anywhere in the line. MATLAB ignores everything right to a
comment. For example,
>>% This is a comment
>>x=2+3 %Declaring variable x
x=
5

18-22 May, 2014 © 2014 UPES


4.3 Writing Script Files
We will write the script files in MATLAB editor. We can create a
script file by the following command:
>> edit <script file name>.
Example
>> edit myfirstscript
 Once we write the commands and save the file, we can call the file
or execute the contents of the file by typing the file name at the
command prompt.
>>myfirstscript

18-22 May, 2014 © 2014 UPES


4.4 Screen showing script file

18-22 May, 2014 © 2014 UPES


4.5 Points to remember while writing script files

 The name of a script file must begin with a letter, and may
include digits and the underscore character, up to 63
characters.

 Do not give a script file the same name as a variable.

 Do not give a script file the same name as a MATLAB


command or function.

 You can check to see if a command, function or file name


already exists by using the exist command.

18-22 May, 2014 © 2014 UPES


4.6 Debugging script files

Program errors usually fall into one of the following


categories.

 Syntax errors such as omitting a parenthesis or comma,


or spelling a command name incorrectly. MATLAB usually
detects the more obvious errors and displays a message
describing the error and its location.

 Errors due to an incorrect mathematical procedure, called


runtime errors. Their occurrence often depends on the
particular input data. A common example is division by
zero.

18-22 May, 2014 © 2014 UPES


4.7 Locating Program Errors

To locate program errors, try the following:

 Test your program with a simple version of the


problem which can be checked by hand.

 Display any intermediate calculations by


removing semicolons at the end of
statements.

 Use the debugging features of the


Editor/Debugger.
18-22 May, 2014 © 2014 UPES
4.8 Programming Style

1. Comments section
a. The name of the program and any key words in the first
line.
b. The date created, and the creators' names in the second
line.
c. The definitions of the variable names for every input and
output variable. Include definitions of variables used in the
calculations and units of measurement for all input and all
output variables!

d. The name of every user-defined function called by the


program.

18-22 May, 2014 © 2014 UPES


4.8 Programming Style Contd…

2. Input section: Include input data and /or the input functions
and comments for documentation.

3. Calculation section: Include formulas/ commands on the input


variables.

4. Output section: This section might contains functions for


displaying the output onto the screen.

18-22 May, 2014 © 2014 UPES


4.9 Input/Output commands while writing scripts

18-22 May, 2014 © 2014 UPES


4.10 Example of a script file

Problem:

The speed v of a falling object dropped with no initial


velocity is given as a function of time t by v = gt.

Plot v as a function of t for 0 < t < tfinal, where tfinal is


the final time entered by the user.

18-22 May, 2014 © 2014 UPES


4.11 Example of a script file Contd…

% Program falling_speed.m:
% Plots speed of a falling object.
% Created on May 18, 2014
%
% Input Variable:
% tfinal = final time (in seconds)
%
% Output Variables:
% t = array of times at which speed is
% computed (in seconds)
% v = array of speeds (meters/second)
%
18-22 May, 2014 © 2014 UPES
4.11 Example of a script file Contd…
% Parameter Value:
g = 9.81; % Acceleration in SI units
%
% Input section:
tfinal = input(’Enter final time in seconds:’);
%
% Calculation section:
dt = tfinal/500;
% Create an array of 501 time values.
t = 0:dt:tfinal;
% Compute speed values.
v = g*t;
%
% Output section:
Plot(t,v),xlabel(’t (s)’),ylabel(’v m/s)’)

18-22 May, 2014 © 2014 UPES


Questions ???

18-22 May, 2014 © 2014 UPES


DAY I: Lecture 5

Working with Function files


(User defined functions)

18-22 May, 2014 © 2014 UPES


5.1 Function Files in MATLAB
 A function file is a M-file, similar to script file, except it
has a function definition line at the top that defines the
inputs and outputs explicitly.
 All the variables in a function file are local, which
means their values are available only within the
function.
 Function files are useful when you need to repeat a
set of commands several times.
 Functions are the building blocks of larger program.

18-22 May, 2014 © 2014 UPES


5.2 Defining Functions
 The first line in a function file must begin with a function
definition line that has a list of inputs and outputs. This line
distinguishes a function M-file from a script M-file. Its syntax is
as follows:
function [output variables] = name(input variables)
 Note that the output variables are enclosed in square brackets,
while the input variables must be enclosed with parentheses.
The function name (here, name) should be the same as the file
name in which it is saved (with the .m extension).

18-22 May, 2014 © 2014 UPES


5.3 User defined Functions: Example

function z = fun(x,y)
u = 3*x;
z = u + 6*y.^2;
 Note the use of a semicolon at the end of the
lines. This prevents the values of u and z from
being displayed.
 Note also the use of the array exponentiation
operator (.^). This enables the function to
accept y as an array.
18-22 May, 2014 © 2014 UPES
5.4 User defined Functions: Example contd..

Call this function with its output argument:


>>z = fun(3,7)
z =
303
The function uses x = 3 and y = 7 to compute z.

18-22 May, 2014 © 2014 UPES


5.4 User defined Functions: Example contd..
Call this function without its output argument and try to
access its value. You will see an error message.
>>fun(3,7)
ans =
303
>>z
??? Undefined function or variable
’z’.
18-22 May, 2014 © 2014 UPES
5.4 User defined Functions: Example contd..
 Assign the output argument to another variable:
>>q = fun(3,7)
q =
303
 You can suppress the output by putting a semicolon
after the function call.
 For example, if you type q = fun(3,7); the value
of q will be computed but not displayed (because of
the semicolon).
18-22 May, 2014 © 2014 UPES
5.5 Function with more than one output
 A function may have more than one output. These are enclosed in square
brackets.
 For example, the function circle computes the area A and circumference
C of a circle, given its radius as an input argument.
function [A, C] = circle(r)
A = pi*r.^2;
C = 2*pi*r;

The function is called as follows, if the radius is 4.


>>[A, C] = circle(4)
A =
50.2655
C =
25.1327

18-22 May, 2014 © 2014 UPES


5.6 Function with no input/output arguments
 The function show_date clears all variables,
clears the screen, computes and stores the
date in the variable today, and then displays
the value of today.

function show_date
clear
clc
today = date

18-22 May, 2014 © 2014 UPES


5.7 Examples of function definition lines
1. One input, one output:
function [area_square] = square(side)
2. Brackets are optional for one input, one output:
function area_square = square(side)
3. Three inputs, one output:
function [volume_box] = box(height,width,length)
4. One input, two outputs:
function [area_circle,circumf] = circle(radius)
5. No named output:
function sqplot(side)
18-22 May, 2014 © 2014 UPES
5.8 Global variable declaration
 The global command declares certain variables
global, and therefore their values are available to the
basic workspace and to other functions that declare
these variables global.
 The syntax to declare the variables a, x, and q is
global a x q
 Any assignment to those variables, in any function or
in the base workspace, is available to all the other
functions declaring them global.

18-22 May, 2014 © 2014 UPES


5.9 Function Handles
 You can create a function handle to any function by using the at
sign, @, before the function name. This acts as a reference to a
given function. You can then use the handle to reference the
function. To create a handle to the function y  x  2ex 3,
define the following function file:

function y = f1(x)
y = x + 2*exp(-x) - 3;

To create a handle to this function and name the handle fh1, you
type fh1=@f1

18-22 May, 2014 © 2014 UPES


Questions ???

18-22 May, 2014 © 2014 UPES


DAY I: Lecture 6

Working with Files and


Directories

18-22 May, 2014 © 2014 UPES


6.0 Directories and Path
 It is important to know the location of the files you use with MATLAB.
 File location frequently causes problems for beginners.
 Files are stored in directories called folders. Directories have sub directories
below them. Your MATLAB system should be smart enough to identify the
directory in which a particular file of your work is stored.
 For example, if the MATLAB is stored in c: in the directory c:\matlab, then
the toolbox directory is a subdirectory under c:\matlab, and symbolic is a
subdirectory under toolbox directory.
 The path tells us and MATLAB how to find a particular file.
 We should update MATLAB with the location in which our files are located in
order to execute them by setting the path. Otherwise, MATLAB cannot
understand the command you have given.

18-22 May, 2014 © 2014 UPES


6.1 Understanding the Whereabouts

 Where are You - Current working Directory


>> dir (or) >> pwd (print working directory)
 Changing current working directory
 Contents of working directory
>> ls (or) >>dir

18-22 May, 2014 © 2014 UPES


6.2 Understanding MATLAB path
 MATLAB path is a variable, stored under the name path that contains the
paths of all directories that are automatically included in MATLAB’s search
path. By default, all directories that are installed by the MATLAB installer are
included in this path.
 MATLAB includes a default work directory where MATLAB takes you
automatically when you launch MATLAB. So, if you don’t do any directory
navigation, all files that you create and save during a MATLAB session will
be saved in the work directory. However, you are not limited to this directory
for saving your files. You can create a directory anywhere you like on the
computer and access it as mentioned above in How do you change the
current directory. This change, however, is effective only for the duration of
the current session.
 If you prefer to organize your MATLAB files in different directories (other
than work) and would like to have access to all your files automatically each
time you work in MATLAB, you should modify the MATLAB search path with
the path or addpath command to include your directories in the search path.

18-22 May, 2014 © 2014 UPES


6.3 System, Directory and file commands
Command Description
addpath dirname Adds the directory to the search path
cd dirname changes the current directory
dir lists all the files in current directory
dir dirname lists all files in dirname
path displays search path
pathtool starts the set path tool
pwd displays the current directory
rmpath dirname removes dirname from search path

18-22 May, 2014 © 2014 UPES


End of Day I
Questions ???

18-22 May, 2014 © 2014 UPES


DAY II: Lecture 7

Working with Polynomials

18-22 May, 2014 © 2014 UPES


7.0 Polynomials
 Polynomials are mathematical expressions that
are frequently used for problem solving and
modeling in science and engineering. In many
cases an equation that is written in the process
of solving a problem is a polynomial, and the
solution of the problem is the zero of the
polynomial. MATLAB has a wide selection of
functions

18-22 May, 2014 © 2014 UPES


7.1 General Polynomials Functions

conv Multiply Polynomials


deconv Divide Polynomials
poly Polynomials with given roots
polyder Polynomial Derivative
polyfit Polynomial curve fitting
polyval Polynomial Evaluation
residue Partial Fraction Expansion
roots Polynomial roots

18-22 May, 2014 © 2014 UPES


7.2 Declaring a Polynomial in MATLAB
Let
p ( x)  x 4  2 x 3  3 x 2  4 x  5

>> p = [1 2 3 4 5]

Let
p ( x)  6 x  7 x  8
3

>> p= [6 0 7 8]

Note: A Polynomial is entered as a row vector with its elements


as coefficients of various terms of polynomial

18-22 May, 2014 © 2014 UPES


7.3 Multiplying 2 polynomials (Convolution)
Let p=[1 2 3 4 5] and q=[6 7 8]. Then the product of two
polynomials is given by
>> r=conv(p,q)
r=
6 19 40 61 82 67 40
i.e.,

r  6 x  19 x  40 x  61x  82 x  67 x  40
6 5 4 3 2

18-22 May, 2014 © 2014 UPES


7.4 Dividing 2 polynomials (Deconvolution)

If p=[1 2 3 4 5] q=[6 7 8] then


r=conv(p,q)=[6 19 40 61 82 67 40]

Therefore s= r/p =q
i.e., >> s = deconv(r,p)
s=
678

18-22 May, 2014 © 2014 UPES


7.5 Polynomials with specific roots
If the roots are x=2 and x=3 then the polynomial is (x-2)(x-3)
>> r = [2 3];
>> p= poly(r)
p=
1 -5 6
Note: The poly function computes the coefficients of a
polynomial if its roots are known in advance.

18-22 May, 2014 © 2014 UPES


7.6 Derivative of a Polynomial

Polyder function is used to find the derivative of a polynomial by


returning the coefficients of the derivative of the polynomial.
>> p = [1 0 2 3];
>> der=polyder(p)
der=
3 0 2

18-22 May, 2014 © 2014 UPES


7.7 Polynomial Curve Fitting

The polyfit function finds the coefficients of a polynomial that


fits a set of data..
>>x=[0 1 2 3 4 5 6 7 8 9]
>>y=[1 2.5 2 3 3 3 2.5 2.5 2 1]
>>p=polyfit(x,y,3) % Here ‘3’ represents the degree
p=
0.0010 -0.1040 0.8478 1.2028

18-22 May, 2014 © 2014 UPES


7.8 Evaluation of a Polynomial
For evaluating a polynomial we use the polyval function.
>>x=[ 1 0 2];
>>t=0:5
t=
01 2 3 4 5
>>sol=polyval(x,t)
sol= 2 3 6 11 18 27

18-22 May, 2014 © 2014 UPES


7.9 Roots of a Polynomial
>>p=[1 -1 -6];
The above vector represents the coefficients of the
polynomial (x+2)(x-3).
>>r=roots(p)
r=
3
-2

18-22 May, 2014 © 2014 UPES


7.10 Partial Fractions
The command [r p k]=residue(B,A) finds the residues, poles
and direct term of a partial fraction expansion of two
polynomials B(s)/A(s).
Eg.1
Consider (s+1)/s(s+2)
>>n=[1 1];d=conv([1 0],[1 2]);
>>[r p k]=residue(n,d)
r= p= k=
0.5 -2 [] Empty
0.5 0

18-22 May, 2014 © 2014 UPES


7.10 Partial Fractions Contd…
i.e.,

s 1 0.5 0.5
 
s( s  2) s  2 s

18-22 May, 2014 © 2014 UPES


7.10 Partial Fractions Contd…
Example 2:

If f(s)=(s^2+1)/(s^2(s+2))
>>n=[1 0 1];d=poly([0 0 -2]);
>>[r p k]=residue(n,d)
r= p= k=
1.25 -2 [] Empty
-0.25 0
0.5 0

18-22 May, 2014 © 2014 UPES


7.10 Partial Fractions Contd…
Example 3
If the order of numerator and denominator are equal.
F(s)=(3s^2+2s+3)/(s^2+3s+2)
>>n=[3 2 3];d=[1 3 2];
>>[r p k]=residue(n,d)
r= p= k=
-11 -2 3 Not Empty
4 -1
i.e., f(s)= 3 – 11/(s+2) + 4/ (s+1) .

18-22 May, 2014 © 2014 UPES


Questions ???

18-22 May, 2014 © 2014 UPES


DAY II: Lecture 8

Advanced Plotting

18-22 May, 2014 © 2014 UPES


8.0 Multiple plots on the same page
 Multiple plots on the same page can be created with the
subplot command which has the form:
>>subplot(m,n,p)
The above command divides the figure window into m x n
rectangular subplots where plots will be created
Example:
The following code creates the subplots of sine, cosine,
exp and x^2 on the same figure window for x=1:.1:10

18-22 May, 2014 © 2014 UPES


8.0 Multiple plots on the same page Contd..
>>subplot(2,2,1) >> subplot(2,2,3)
>> plot(x,sin(x),'m') >> plot(x,exp(x),'b')
>> xlabel('X') >> xlabel('X')
>> ylabel('Sine Values') >> ylabel('Exponential Values')
>> title('Sine Graph') >> title('Exponential Graph')

>> subplot(2,2,2) >> subplot(2,2,4)


>> plot(x,cos(x),'r') >> plot(x,x.^2,'c')
>> xlabel('X') >> xlabel('X')
>> ylabel('Cosine Values') >> ylabel('Square Values')
>> title('Cosine Graph') >> title('Square Graph')

18-22 May, 2014 © 2014 UPES


8.0 Multiple plots on the same page Contd..

18-22 May, 2014 © 2014 UPES


8.1 ‘3-D’ Plots
 3 D plots can be used to present data that
consists of more than 2 variables. MATLAB
provides various options for displaying 3 D
data which include
 Line Plots
 surface Plots
 mesh plots.

18-22 May, 2014 © 2014 UPES


8.1.1 ‘3-D’ Line Plot
 A three-dimensional line plot is a line that is obtained by
connecting points in a three-dimensional space. A basic
3-D plot is created with the plot3 command, which is very
similar to the plot command, and has the form:
plot3(x,y,z,’line specifiers’,’PropertyName’,property value)
where
 x, y, and z are same length vectors of the coordinates of
the points.
 (Optional) Line Specifiers that define the type and color of
the line and markers.
 (Optional) Properties with values that can be used to
specify the line width, and marker’s size and edge and fill
colors.
18-22 May, 2014 © 2014 UPES
8.1.1 ‘3-D’ Line Plot Contd..
For example, if the coordinates x, y, and z are given as a function of the
parameter t by:
x = sqrt(t) sin(2t), y = sqrt(t) cos(2t), z = 0.5t
A plot of the points for t in between 0 to 6*pi is produced by the
following script file
t=0:0.1:6*pi;
x=sqrt(t).*sin(2*t);
y=sqrt(t).*cos(2*t);
z=0.5*t;
plot3(x,y,z,'k','linewidth',1)
grid on
xlabel('x'); ylabel('y'); zlabel('z')

18-22 May, 2014 © 2014 UPES


8.1.1 ‘3-D’ Line Plot Contd..
The output of the above script is shown below:

18-22 May, 2014 © 2014 UPES


8.1.2 Mesh and Surface Plots
 Mesh and surface plots are 3 D plots that are used for
plotting functions of the form z=f(x,y) where x and y are
the independent variables and z is the dependent
variable. They are created in the following 3 steps:
 Create a grid in the x-y plane that covers the domain of
the function
 Calculate the value of z at each and every grid point
 Create a plot from the calculated values

18-22 May, 2014 © 2014 UPES


8.1.2 Mesh and Surface Plots contd..
 Creation of grid points by meshgrid command
>> x=-1:3;
>> y=1:4;
>> [X,Y]=meshgrid(x,y)
X=
-1 0 1 2 3
-1 0 1 2 3
-1 0 1 2 3
-1 0 1 2 3
Y=
11111
22222
33333
44444

18-22 May, 2014 © 2014 UPES


8.1.2 Mesh and Surface Plots contd..
 Calculation of z values at the grid points
Let z=xy^2/(x^2+y^2)
>> Z = X.*Y.^2./(X.^2 + Y.^2)
Z=
-0.5000 0 0.5000 0.4000 0.3000
-0.8000 0 0.8000 1.0000 0.9231
-0.9000 0 0.9000 1.3846 1.5000
-0.9412 0 0.9412 1.6000 1.9200
18-22 May, 2014 © 2014 UPES
8.1.2 Mesh and Surface Plots contd..
 MAKING MESH PLOT or SURFACE PLOT
>>x=-1:0.1:3;
>>y=1:0.1:4;
>>[X,Y]=meshgrid(x,y);
>>Z=X.*Y.^2./(X.^2+Y.^2);
>>mesh(X,Y,Z) % Use can use surf(X,Y,Z)
>>xlabel('x'); ylabel('y'); zlabel('z')

18-22 May, 2014 © 2014 UPES


8.1.2 Mesh and Surface Plots contd..

Mesh Plot Surface Plot

The mesh plot is made of lines that connect the points. In the surface plot, areas
within the mesh lines are colored.

18-22 May, 2014 © 2014 UPES


8.1.3 3-D Pie Plot
Syntax:
pie3(X,explode)
Example:

>>X=[5 9 14 20];explode=[0 0 1 0];pie3(X,explode)


Note: explode is a vector (same length as X) of 0’s and 1’s.
1 offsets the slice from the center.

The output is shown in the next slide

18-22 May, 2014 © 2014 UPES


8.1.3 3-D Pie Plot Contd..

18-22 May, 2014 © 2014 UPES


Questions ???

18-22 May, 2014 © 2014 UPES


DAY II: Lecture 9

Symbolic Computation

18-22 May, 2014 © 2014 UPES


9.0 Symbolic Math
 Many applications in Engineering and science require
symbolic operations which are mat operations with
expressions containing symbolic variables (variables that do
not have specific numerical values when the operation is
executed)
 The result of such operations is also a mathematical
expression in terms of the symbolic variables.
Examples
 if a, b & x are symbolic variables and ax-b=0, x can be solved
in terms of a & b to give x=b/a.
 The derivative of 2t^3+5t-8 is 6t^2+5.

18-22 May, 2014 © 2014 UPES


9.1 Creating Symbolic Objects
 A symbolic object is a variable name which is created with the
sym or syms commands.
Syntax: >> object_name=sym(‘String’)
Example:
>> a=sym(‘a’) ----’a’ is a symbolic object assigned to a
>>g=sym(‘gamma’)---The symbolic object is gamma assigned
to g.
We can also declare the symbolic variables as shown below:
>> syms a g
‘a’ and ‘g’ are treated as symbolic variables.

18-22 May, 2014 © 2014 UPES


9.2 Creating Symbolic Expressions
 Symbolic expressions are mathematical expressions written in
terms of symbolic variables. Once symbolic variables are
created, they can be used for creating symbolic expressions.
The symbolic expression is a symbolic object.
>> EXPRESSION_NAME=Math expression
Example:
>> syms a b c x y
>> f=a*x^2+b*x + c
f=
a*x^2+b*x+c

18-22 May, 2014 © 2014 UPES


9.2 Creating Symbolic Expressions contd..
 When a symbolic expression, which includes mathematical
operations that can be executed (addition, subtraction,
multiplication, and division), is entered, MATLAB executes the
operations as the expression is created. For example:
>> g=2*a/3+4*a/7-6.5*x+x/3+4*5/3-1.5 produces the
output:
g=
26/21*a-37/6*x+31/6
Notice that all the calculations are carried out exactly with
no numerical approximation.

18-22 May, 2014 © 2014 UPES


9.3 The collect command
 The collect command collects the terms in the expression that have
the variable with the same power. In the new expression, the terms
will be ordered in decreasing order of power. The command has the
forms:
 >> collect(S), where S is the expression
The collect(S) form works best when an expression has only one
symbolic variable.
>> syms x y
>> S=(x^2+x-exp(x))*(x+3)
S=
(x^2 + x-exp(x))*(x + 3)
>> F = collect(S)
F=
x^3+4*x^2+(-exp(x)+3)*x-3*exp(x)

18-22 May, 2014 © 2014 UPES


9.4 The expand command
 The expand command expands expressions in two ways. It
carries out products of terms that include summation (at
least one of the terms), and it uses trigonometric identities
and exponential and logarithmic laws to expand
corresponding terms that include summation. The form of
the command is:
>> expand(S), where S is the expression
Example 1:
>> syms a x y; S=(x+5)*(x-a)*(x+4)
S=
(x+5)*(x-a)*(x+4)
>> T=expand(S)
T=
x^3+9*x^2-x^2*a-9*x*a+20*x-20*a

18-22 May, 2014 © 2014 UPES


9.4 The expand command contd…
Example 2:
>>expand(sin(x-y))
ans =
sin(x)*cos(y)-cos(x)*sin(y)

18-22 May, 2014 © 2014 UPES


9.5 The factor command
 The factor command changes an expression that is a
polynomial to be a product of polynomials of a lower degree.
The form of the command is:
 >>factor(S) % S is the symbolic expression
>> syms x
>> S=x^3+4*x^2-11*x-30
S=
x^3+4*x^2-11*x-30
>> factor(S)
ans =
(x+2)*(x-3)*(x+5)

18-22 May, 2014 © 2014 UPES


9.6 The simplify command
 The simplify command uses mathematical operations (addition,
multiplication, rules of fractions, powers, logarithms, etc.) and functional
and trigonometric identities to generate a simpler form of the
expression. The format of the simplify command is:
>>simplify (S) % S is the symbolic expression
>> syms x y
>> S=x*(x*(x-8)+10)-5
S=
x*(x*(x - 8) + 10) - 5
>> SA = simplify(S)
SA =
x^3-8*x^2+10*x-5
>> simplify((x+y)/(1/x+1/y))
ans =
x*y
18-22 May, 2014 © 2014 UPES
9.7 The pretty command
The pretty command displays a symbolic expression in a format
resembling the mathematical format in which expressions are
generally typed. The command has the form:
>> pretty(S)
>> syms a b c x
>> S=sqrt(a*x^2 + b*x + c)
S=
(a*x^2+b*x+c)^(1/2)
>> pretty(S)
𝟏
𝒂𝒙𝟐 + 𝒃𝒙 + 𝒄 𝟐

18-22 May, 2014 © 2014 UPES


9.8 The solve function
The solve function is used to solve equations.
>> h=solve(equation)
>> syms a b x y z >> T= a*x^2+5*b*x+20
>> h=solve(exp(2*z)-5) T=
h= a*x^2+5*b*x+20
1/2*log(5) >> solve(T)
>> S=x^2-x-6 ans =
S= [ 1/2/a*(-5*b+(25*b^2-80*a)^(1/2))]
x^2-x-6 [ 1/2/a*(-5*b-(25*b^2-80*a)^(1/2))]
>> k=solve(S)
k= >> M = solve(T,a)
[ -2] M=
[ 3] -5*(b*x+4)/x^2
>> solve('cos(2*y)+3*sin(y)=2')
ans = >> gs=solve('4*t*h^2+20*t-5*g','g')
[ 1/2*pi] gs =
[ 1/6*pi] 4/5*t*h^2+4*t
[ 5/6*pi]
18-22 May, 2014 © 2014 UPES
9.9 Solving System of Equations
The solve function is used to solve a system of equations.
>> output = solve(eq1,eq2,....,eqn)

>> sol=solve('3*x-5*y=30','x+5*y=50')
sol =
x: [1x1 sym]
y: [1x1 sym]
>> sol.x=20
>>sol.y=6

18-22 May, 2014 © 2014 UPES


9.9 Solving System of Equations contd..
>> syms x y t
>> S=10*x+12*y+16*t;
>> [xt yt]=solve(S, '5*x-y=13*t')
xt =
2*t
yt =
-3*t
In the example above, notice that the system of two
equations is solved by MATLAB for x and y in terms of t,
since x and y are the first two variables in the default
order.
18-22 May, 2014 © 2014 UPES
9.9 Solving System of Equations contd..
 The system, however, can be solved for different variables. As an
example,the system is solved next for y and t in terms of x (using
the second form of the solve command:
>> [tx yx]=solve(S,'5*x-y=13*t',y,t)
tx =
1/2*x
yx =
-3/2*x
 The variables for which the system is solved (y and t) are
entered.
 The solution for the variables for which the system is solved is
assigned in alphabetical order. The first cell has the solution for t,
and the second cell has the solution for y.

18-22 May, 2014 © 2014 UPES


9.10 Differentiation
 Symbolic differentiation can be carried out by using the diff
command. The form of the command is:
diff(S) or diff(S,var)
>> syms x y t >> diff(R,t)
>> S=exp(x^4); ans =
>> diff(S) -15*y^2*sin(3*t)
ans =
4*x^3*exp(x^4) >> diff(S,2)
ans =
>> diff((1-4*x)^3) 12*x^2*exp(x^4)+16*x^6*exp(x^4)
ans =
-12*(1-4*x)^2

>> R=5*y^2*cos(3*t);
>> diff(R)
ans =
10*y*cos(3*t)

18-22 May, 2014 © 2014 UPES


9.11 Integration
 Symbolic integration can be carried out by
using the int command.
For indefinite integration the command is
int(S) or int(S,var)
For definite integration the form of the
command is:
int(S,a,b) or int(S,var,a,b)

18-22 May, 2014 © 2014 UPES


9.11 Integration contd…
>> syms x y t
>> syms y
>> S=2*cos(x)-6*x;
>> int(S) >> int(sin(y)-5*y^2,0,pi)
ans =
2*sin(x)-3*x^2
ans =
>> int(x*sin(x)) 2-5/3*pi^3
ans =
sin(x)-x*cos(x)
>>R=5*y^2*cos(4*t);
>> int(R)
ans =
5/3*y^3*cos(4*t)
>> int(R,t)
ans =
5/4*y^2*sin(4*t)

18-22 May, 2014 © 2014 UPES


9.12 Other important commands

• dsolve – to solve ordinary differential


equations
• subs – to substitute values in symbolic
expressions
• Taylor – to get taylor’s series expansion of
functions
• ezplot – to plot symbolic expressions

18-22 May, 2014 © 2014 UPES


Questions ???

18-22 May, 2014 © 2014 UPES


DAY III: Lecture 10

Programming in MATLAB

18-22 May, 2014 © 2014 UPES


10.0 Algorithms and Control structures
Algorithm: an ordered sequence of precisely defined instructions
that performs some task in a finite amount of time. Ordered
means that the instructions can be numbered, but an algorithm
must have the ability to alter the order of its instructions using a
control structure. There are three categories of algorithmic
operations:

Sequential operations: Instructions executed in order.

Conditional operations: Control structures that first ask a


question to be answered with a true/false answer and then select
the next instruction based on the answer.

Iterative operations (loops): Control structures that repeat the


execution of a block of instructions.
 18-22 May, 2014 © 2014 UPES
10.1 Relational Operators

Operator Meaning

< Less than.


<= Less than or equal to.
> Greater than.
>= Greater than or equal to.
== Equal to.
~= Not equal to.

18-22 May, 2014 © 2014 UPES


10.1 Relational Operators contd…
For example, suppose that x = [6,3,9] and y = [14,2,9].
The following MATLAB session shows some examples.

>>z = (x < y)
z =
1 0 0
>>z = (x ~= y)
z =
1 1 0
>>z = (x > 8)
z =
0 0 1

18-22 May, 2014 © 2014 UPES


10.1 Relational Operators contd…

The relational operators can be used for array


addressing.

For example, with x = [6,3,9] and y =


[14,2,9], typing

z = x(x<y)

finds all the elements in x that are less than the


corresponding elements in y. The result is z = 6.

18-22 May, 2014 © 2014 UPES


10.1 Relational Operators contd…

The arithmetic operators +, -, *, /, and \ have precedence over


the relational operators. Thus the statement

z = 5 > 2 + 7

is equivalent to

z = 5 >(2+7)

and returns the result z = 0.

We can use parentheses to change the order of precedence;


for example, z = (5 > 2) + 7 evaluates to z = 8.

18-22 May, 2014 © 2014 UPES


10.2 Logical operators
Operator Name Definition

~ NOT ~A returns an array the same dimension as A; the


new array has ones where A is zero and zeros
where A is nonzero.

& AND A & B returns an array the same dimension as A and


B;the new array has ones where both A and B have
nonzero elements and zeros where either A or B is
zero.

| OR A | B returns an array the same dimension as A and


B;the new array has ones where at least one element
in A or B is nonzero and zeros where A and B are
both zero.

18-22 May, 2014 © 2014 UPES


10.3 Logical functions
Logical function Definition

ischar(A) Returns a 1 if A is a character array and 0 otherwise.


isempty(A) Returns a 1 if A is an empty matrix and 0 otherwise.
isinf(A) Returns an array of the same dimension as A, with ones
where A has ‘inf’ and zeros elsewhere.
isnan(A) Returns an array of the same dimension as A with ones
where A has ‘NaN’ and zeros elsewhere.

(‘NaN’ stands for “not a number,” which means an undefined result.)

18-22 May, 2014 © 2014 UPES


10.4 The if Statement

The if statement’s basic form is

if logical expression
statements
end

Every if statement must have an accompanying


end statement. The end statement marks the end of
the statements that are to be executed if the logical
expression is true.

18-22 May, 2014 © 2014 UPES


10.5 The else Statement

The else Statement

The basic structure for the use of the else


statement is

if logical expression
statement group 1
else
statement group 2
end

18-22 May, 2014 © 2014 UPES


10.5 Flowchart of the else statement

18-22 May, 2014 © 2014 UPES


10.6 Example of the else statement
For example, if we fail to recognize how the test works, the following
statements do not perform the way we might expect.

x = [4,-9,25];
if x < 0
disp(’Some of the elements of x are negative.’)
else
y = sqrt(x)
end

When this program is run it gives the result

y =
2 0 + 3.000i 5

18-22 May, 2014 © 2014 UPES


10.6 Example of the else statement contd..
x = [4,-9,25];
if x >= 0
y = sqrt(x)
else
disp(’Some of the elements of x are
negative.’)
end

When executed, it produces the following message:

Some of the elements of x are negative.

18-22 May, 2014 © 2014 UPES


10.7 Nested Ifs
if logical expression 1
if logical expression 2
statements
end
end

can be replaced with the more concise program

if logical expression 1 & logical


expression 2
statements
end

18-22 May, 2014 © 2014 UPES


10.8 The elseif statement
The general form of the if statement is

if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
else
statement group 3
end

The else and elseif statements may be omitted if not


required. However, if both are used, the else statement
must come after the elseif statement to take care of all
conditions that might be unaccounted for.
18-22 May, 2014 © 2014 UPES
10.9 Flowchart of the general if- elseif-else
statement

18-22 May, 2014 © 2014 UPES


10.10 An Example
For example, suppose that y = log(x) for x > 10, y
=sqrt(x) for 0 <= x <= 10, and y = exp(x) - 1 for
x < 0. The following statements will compute y if x already
has a scalar value.

if x > 10
y = log(x)
elseif x >= 0
y = sqrt(x)
else
y = exp(x) - 1
end

18-22 May, 2014 © 2014 UPES


10.11 The for loop
A simple example of a for loop is

for k = 5:10:35
x = k^2
end

The loop variable k is initially assigned the value 5, and x is


calculated from x = k^2. Each successive pass through
the loop increments k by 10 and calculates x until k exceeds
35. Thus k takes on the values 5, 15, 25, and 35, and x
takes on the values 25, 225, 625, and 1225. The program
then continues to execute any statements following the end
statement.

18-22 May, 2014 © 2014 UPES


10.12 Flow chart of the for loop

18-22 May, 2014 © 2014 UPES


10.13 An Example of continue statement
For example, the following code uses a continue statement
to avoid computing the logarithm of a negative number.

x = [10,1000,-10,100];
y = NaN*x;
for k = 1:length(x)
if x(k) < 0
continue
end
y(k) = log10(x(k));
end
y
The result is y = 1, 3, NaN, 2.

18-22 May, 2014 © 2014 UPES


10.14 While loop
The while loop is used when the looping process
terminates because a specified condition is satisfied, and
thus the number of passes is not known in advance. A
simple example of a while loop is

x = 5;
while x < 25
disp(x)
x = 2*x - 1;
end

The results displayed by the disp statement are 5, 9, and


17.

18-22 May, 2014 © 2014 UPES


10.15 More on While loop
The typical structure of a while loop follows.

while logical expression


statements
end

For the while loop to function properly, the following two


conditions must occur:

1. The loop variable must have a value before the while


statement is executed.

2. The loop variable must be changed somehow by the


statements.

18-22 May, 2014 © 2014 UPES


10.16 Flowchart of While loop

18-22 May, 2014 © 2014 UPES


10.17 The switch structure

The switch structure provides an


alternative to using the if, elseif, and
else commands.Anything programmed
using switch can also be programmed
using if structures.

However, for some applications the switch


structure is more readable than code using
the if structure.

18-22 May, 2014 © 2014 UPES


10.18 Syntax of the switch structure
switch input expression (can be a
scalar or string).
case value1
statement group 1
case value2
statement group 2
.
.
.
otherwise
statement group n
end

18-22 May, 2014 © 2014 UPES


10.19 Example of the switch structure
The following switch block displays the point on the
compass that corresponds to that angle.

switch angle
case 45
disp(’Northeast’)
case 135
disp(’Southeast’)
case 225
disp(’Southwest’)
case 315
disp(’Northwest’)
otherwise
disp(’Direction Unknown’)
end
18-22 May, 2014 © 2014 UPES
10.20 The break command
When inside a loop the break command terminates the
execution of the loop.

In nested loops,if the break command is


inside a nested loop, only the nested loop
is terminated.

When a break command appears outside a loop


in a script or function file, it terminates
the execution of the file.

It is usually used within the conditional


statements.

18-22 May, 2014 © 2014 UPES


10.20 The break command example
for i=1:10
if (i>5)
break;
else
disp(i)
end
end

The above loop prints 1 2 3 4 5

18-22 May, 2014 © 2014 UPES


Questions ???

18-22 May, 2014 © 2014 UPES

You might also like