SESSION-1
Introduction to MATLAB
What is MATLAB
MATLAB is an high-level language and
mathematical programming environment for:
Visualization
Programming, algorithm development
Numerical computation: linear algebra,
optimization, control, statistics, signal and image
processing, etc.
MATLAB is a proprietary software of MathWorks
2
Starting and Stopping
To Start MATLAB
On Microsoft® Windows® platforms,
double-clicking the MATLAB shortcut on
your Windows desktop.
On UNIX platforms, start MATLAB by typing
MATLAB at the operating system prompt.
Quitting the MATLAB Program
To end your MATLAB session, select File >
Exit MATLAB in the desktop, or type quit in
the Command Window
3
The MATLAB System
MATLAB system consists of these main parts:
Desktop Tools and Development
Environment
Includes the MATLAB desktop and MATLAB
Terminal, an editor and debugger, a code
analyzer, browsers for viewing help, the
workspace, files, and other tools
Mathematical Function Library
Vast collection of computational algorithms
ranging from elementary functions, like sine,
cosine, and complex arithmetic, to more
4 sophisticated functions like matrix inverse,
matrix eigenvalues, Bessel functions, and fast
The Language
The MATLAB language is a high-level
matrix/array language with control flow
statements, functions, data structures,
input/output, and object-oriented programming
features.
Graphics
MATLAB has extensive facilities for displaying
vectors and matrices as graphs, as well as
editing and printing these graphs. It also
includes functions that allow you to customize
the appearance of graphics as well as build
complete graphical user interfaces on your
MATLAB applications.
5
Main MATLAB Window
6
MATLAB Windows
Command Window
The Command Window is MATLAB’s main
window and opens when MATLAB is started.
MATLAB commands are entered here. A prompt
appears on the screen and a MATLAB
statement can be entered. When the <ENTER>
key is pressed, the statement is executed, and
another prompt appears
Workspace Window
Displays any variables created (Matrices,
Vectors, Singles, etc.)
Command History Window
7
Lists all commands previously entered.
Figure Window
The Figure Window opens automatically When
graphics commands are executed and
contains graphs created by these commands.
Editor Window
The Editor Window is used for writing and
editing programs. This from file menu .
Help Window
The Help Window contains help information.
This window can be opened from the help
menu in the toolbar of any MATLAB.
8
Working in Command
Window
To type a command the cursor must be placed
next to the command prompt ( >> ).
Once a command is typed and the Enter key is
pressed, the command is executed.
It is not possible to go back to a previous line
that is displayed in the Command
A previously typed command can be recalled to
the command prompt with the up-arrow key
( )..
If a command is too long to fit in one line, it
can be continued to the next line by typing
three periods … (called an ellipsis) and
pressing the Enter key.
9
Arithmetic Operations
Operation Symbol Precedence
Exponentiation ^ Second
Right division / Third
Left division \ Third
Multiplication * Third
Addition + Fourth
Subtraction - Fourth
10
General Commands
Command Symbol
help Lists topics on which help is available.
helpwin Opens the interactive help window.
Opens the web browser based help
helpdesk facility.
help topic Provides help on topic.
lookfor
Lists help topics containing string.
string
demo Runs the demo program.
Clears MATLAB Terminal, command
clc history is lost.
clf Clears figure window.
Tells you the computer type you are
11
computer using.
Gives you wall clock time and date as a
Display Formats
12
Display Formats (Cont.)
13
Elementary Math Functions
14
Trigonometric Math
Functions
15
Rounding Functions
16
Defining scalar variables
A variable is a name made of a letters and
digits that is assigned a numerical value.
A variable is actually a name of a memory
location.
When a new variable is defined, MATLAB
allocates an appropriate memory space
where the variable’s assignment is stored
MATLAB is case sensitive: it distinguishes
between uppercase and lowercase letters. For
example, AA, Aa, aA, and aa are the names of
four different variables.
Avoid using the name of a built-in function for
17
a variable (i.e., avoid using cos, sin, exp, sqrt,
Commands for Managing
variables
Command Description
Removes all variables from the
clear
memory.
Clears/removes only variables x, y
clear x, y, z
and z from the memory.
Lists the variables currently in the
who
workspace.
Displays a list of the variables
currently in the memory and their
whos
size together with information
about their bytes and class.
18
Predefined variables
Variable Description
Represents a value computed by
an expression but not stored in
ans variable name.
pi Represents the number π.
The smallest difference between
eps two numbers
inf Used for infinity
Defined as −1 , which is: 0 +
i 1.0000i.
j Same as i.
Stands for Not-a-Number. Used
19
when MATLAB cannot determine a
Script and Functions Files
Script Files
A script file is a sequence of MATLAB commands,
also called a program.
When a script file runs MATLAB executes the
commands in the order they are written and the
output is displayed in the MATLAB Terminal.
Using a script file is convenient because it can be
edited and executed many times.
Script files are also called M-files because the
extension .m is used when they are saved.
Functions Files ,
Which can accept input arguments and return
20 output arguments. Internal variables are local to
the function.
Working with Matrices and
Arrays
Since MATLAB makes extensive use of matrices, the
best way for you to get started with MATLAB is to
learn how to handle matrices.
Separate the elements of a row with blanks or
commas.
Use a semicolon ; to indicate the end of each row.
Surround the entire list of elements with square
brackets, [ ].
A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14
1]
21
MATLAB displays the matrix you just entered:
A=
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
Once you have entered the matrix, it is
automatically remembered in the MATLAB
workspace. You can simply refer to it as A.
Keep in mind, variable names are case-sensitive
When you do not specify an output variable,
22
MATLAB uses the variable ans, short for answer,
Subscripts
The element in row i and column j of A
is given by A(i,j).
So to compute the sum of the elements in the
fourth
column of A, we have:
A(1,4) + A(2,4) + A(3,4) + A(4,4)
Which produces:
ans = 34
23
The Colon Operator
For example: 1:10
is a row vector containing the integers from 1 to
10:
1 2 3 4 5 6 7 8 9 10
To obtain non-unit spacing, specify an increment.
For example: 100:-7:50 will give you
100 93 86 79 72 65 58 51
Subscript expressions involving colons refer to
portions of a matrix. For example: A(1:k,j)
refers to the first k elements of the jth column of
A.
24
Array Addressing
A colon can be used in MATLAB to address a range
of elements in a vector or a matrix
Colon for a vector
Va(:) – refers to all the elements of the vector Va
(either a row or a column vector).
Va(m:n) – refers to elements m through n of the
vector Va.
For Example,
>> V = [2 5 –1 11 8 4 7 –3 11]
>> u = V (2 :8)
u = 5 –1 11 8 4 7 –3 11
25
Array Addressing
Colon for a matrix
Table gives the use of a colon in addressing arrays
in a matrix
Variable Description
Refers to the elements in all the
A(:, n) rows of a column n of the matrix A.
Refers to the elements in all the
A(n, :) columns of row n of the matrix A.
Refers to the elements in all the
rows between columns m and n of
A(:, m:n) the matrix A.
Refers to the elements in all the
columns between rows m and n of
A(m:n, :) the matrix A.
26 Refers to the elements in rows m
Operation on matrices
Multiplication of matrices with * calculates inner
products between rows and columns
Addition and Subtraction of Matrices obtained by
adding or subtracting their corresponding
elements.
To transpose a matrix, use ‘
det(A) calculates the determinant of a matrix A
inv(A) calculates the inverse of a matrix A
pinv(A) calculates the pseudo-inverse of a matrix
A
27
Graphics
• MATLAB provides a variety of techniques to
display data graphically.
• Interactive tools enable you to manipulate
graphs to achieve results that reveal the most
information about your data.
• You can also edit and print graphs for
presentations, or export graphs to standard
graphics formats for presentation in Web
browsers or other media.
28
Basic Plotting Functions
The basic command for producing a simple 2-D
plot is
plot(x values, y values, ‘style option’)
where
x values and y values are vectors containing the
x- and y-coordinates of points on the graph.
Style option is an optional argument that specifies
the color, line-style and the point-marker style.
There are several specialized graphics functions
available in MATLAB for 2-D plots.
29
Basic Plotting Commands
Variable Description
grid Displays gridlines.
print Prints plot or saves plot to a file
title Puts text at top of plot.
xlabel Adds text label to x-axis.
ylabel Adds text label to y-axis.
close Closes the current plot.
close all Closes all plots.
figure Opens a new figure window.
hold Freezes current plot.
legend Legend placement by mouse.
Specifies properties of objects such
set as axes.
30 subplot Creates plots in subwindows.
Specialized Plot Commands
Variable Description
bar Creates bar chart.
loglog Creates log-log plot.
polar Creates polar plot.
Creates semilog plot (logarithmic
semilogx abscissa).
Creates semilog plot (logarithmic
semilogy ordinate).
stairs Creates stairs pot.
stem Creates stem plot.
31
Example: x=[0:2*pi]
y=sin(x)
plot(x,y)
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine
Function','FontSize',12)
32
Plotting Multiple Data Sets in
One Graph
Multiple x-y pair arguments create multiple
graphs with a single call to plot.
For example:
x = 0:pi/100:2*pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
33
Adding Plots to an Existing
Graph
When you type: hold on
MATLAB does not replace the existing graph when
you issue another plotting command; it adds the
new data to the current graph, rescaling the axes
if necessary.
Graphing Imaginary and
Complex Data
34 When the arguments to plot are complex, the
imaginary part is ignored except when you use a
Figure Windows
Graphing functions automatically open a new
figure window if there are no figure windows
already on the screen.
To make a figure window the current figure,
type
figure(n)
where n is the number in the figure title
bar. The results of subsequent graphics
commands are displayed in this window.
35
Specifying Line Styles and
Colors
It is possible to specify color, line styles, and
markers (such as plus signs or circles) when you
plot your data using the plot command:
plot(x,y,'color_style_marker')
36
Displaying Multiple Plots in One Figure
subplot(m,n,p)
This splits the figure window into an m-by-n
matrix of small subplots and selects the pth
subplot for the current plot.
Example:
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)
37
Controlling the Axes
Setting Axis Limits & Grids
The axis command lets you to specify your own
limits: axis([xmin xmax ymin
ymax])
You can use the axis command to make the axes
visible or invisible: axis on / axis off
The grid command toggles grid lines on and off:
grid on / grid off
38
Control statement
If ,if else
For loop
While loop
Switch case
Brake ,continue etc.
3 6/4/2015
9
IF
price=4500;
if price >5000,
disp('PRICE IS MORE THAN 5000');
end
40 Dilip Mandloi
IF ELSE
price=4500;
if price >5000,
disp('PRICE IS MORE THAN 5000');
else
disp(‘PRICE IS NOT MORE THAN 5000’);
end
41
IF ELSEIF
price=4500;
if price >5000,
disp('PRICE IS MORE THAN 5000');
elseif (1000<=price)&(price <=5000),
disp('PRICE IS BETWEEN 1000 AND 5000');
else
disp('PRICE IS LESS THAN 1000');
end
42
WHILE LOOP
var=20;
while var>0,
disp(var);
var=var-1;
end
disp('variable is zero now');
disp(var);
43
FOR LOOP
for i=1:10,
disp(i);
end
for i=1:2:11,
disp(i)
end
44
Nested For Loop
n=3;
for i=1:n,
for j=1:n,
a(i,j)=5;
end
end
disp(a);
45
SWITCH CASE
var1=10;
var2=5;
switch operation
case 'add'
output=var1+var2;
disp(output);
case {'multiply','product'}
output=var1*var2;
disp(output);
46
CONTINUED ……….
case {'subtract','sub'}
output=var1-var2;
disp(output);
case 'divide'
output=var1/var2;
disp(output);
otherwise
disp('What else you want?');
end
47
CONTINUED…….
case {'subtract','sub'}
output=var1-var2;
disp(output);
case 'divide'
output=var1/var2;
disp(output);
otherwise
disp('What else you want?');
end
48
Thank you
49