P R E S E N T E D B Y :
SHAHNAWAZ UDDIN
UNIVERSITY WOMEN’S POLYTECHNIC AMU ALIGARH
Introduction to
MATLAB
OUTLINE
What is MATLAB?
Its main features
What are we interested in?
Starting MATLAB - MATLAB GUI
- Interactive commands - MATLAB operators
- ….
What is MATLAB?
• MATLAB is a simple programming language with its own extensive library of mathematical and graphical subroutines
• Originally designed for solving linear algebra type problems using matrices. It’s name is derived from MATrix
LABoratory.
• MATLAB has expanded and now has built-in functions for
– solving problems requiring data analysis
– signal processing
– …..
– ……
– several other types of scientific computations.
– Powerful 2-D and 3-D graphics and animation.
What is MATLAB?
• If MATLAB can process and visualize data, why ever use FORTRAN, C, or some other language?
• Identical code executes more slowly, sometimes MUCH more slowly in MATLAB
What is Matlab?
• Matlab is basically a high level language which has many specialized toolboxes for making things easier for us
• How high?
Assembly
High Level Languages such as
C, Pascal etc.
Matlab
Main Features
Simple programming rules
Comprehensive mathematical library
Extensive graphics tools
The MATLAB environment is command oriented like UNIX or DOS.
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.
What are we interested in?
Matlab is too broad for our purposes in this course.
The features we are going to require is Matlab
Command m-files Line
functions
mat-files
Command execution like DOS command
window Series of
Matlab commands
Input Output capability
Data storage/
loading
Starting MATLAB
Command Window
Command History Working Directory
Workspace
MATLAB GUI
• Current Folder Window
– Displays contents of the current working directory
– MATLAB Search Path
• Path that MATLAB uses to search for script and function files
• Default path contains all built in MATLAB functions
• Can modify path through MATLAB function or going under File>Set Path
• MATLAB will ask to modify path if
running a program from a folder not in path
MATLAB GUI
• Workspace Window
– Shows all currently defined variables
– Array dimensions
– Min, max values
– Good debugging tool
• Command History
– Shows all paste commands
– Can copy and paste commands into command window
– Double click will execute command
MATLAB GUI
• Desktop Menus
• File Menu
– New
• Create new MATLAB program file (m-file)
– Open existing m-file
– Import data
– Set Path
– Open recent m-files
MATLAB GUI
Edit Menu
Copy, cut, paste
Find and replace phrases
Clear command history, workspace
Desktop Menu
Change appearance of desktop
Select windows to display
Interactive Commands
Enter commands at >> prompt
Variable ‘x’ automatically allocated
MATLAB does not require declaration of variables
Interactive Commands
MATLAB is case sensitive
Variable ‘ans’ will take value of
result of command if no equal sign specified
Holds most recent result only
Semicolon at end of line will
suppress output, it is not required like in C
Useful in script files and debugging
Interactive Commands
Format of output
Defaults to 4 decimal places
Can change using format statement
format long changes output to 15 decimal places
MATLAB Special Variables
ans Default variable name for results
pi Value of
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0 i and j i = j = square root of -1
realmin The smallest usable positive real number realmax The largest usable positive real number
MATLAB Math & Assignment Operators
Power ^ or .^ a^b or a.^b
Multiplication * or .* a*b or a.*b
Division / or ./ a/b or a./b
or \ or .\ b\a or b.\a
NOTE: 56/8 = 8\56
Addition + a + b
Subtraction - a - b
Assignment = a = b (assign b to a)
MATLAB Relational Operators
MATLAB supports six relational operators.
Less Than <
Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~=
MATLAB Logical Operators
MATLAB supports three logical operators.
not ~ % highest precedence
and & % equal precedence with or or | % equal precedence with and
MATLAB Logical Functions
MATLAB also supports some logical functions.
xor (exclusive or) Ex: xor (a, b)
Where a and b are logical expressions. The xor operator evaluates to true if and only if one
expression is true and the other is false. True is returned as 1, false as 0.
any (x) returns 1 if any element of x is nonzero all (x) returns 1 if all elements of x are
nonzero
isnan (x) returns 1 at each NaN in x isinf (x) returns 1 at each infinity in x
Other MATLAB symbols
>> prompt
. . . continue statement on next line , separate statements and data
% start comment which ends at end of line
; (1) suppress output
(2) used as a row separator in a matrix
: specify range
Array, Matrix
a vector x = [1 2 5 1]
x =
1 2 5 1
a matrix x = [1 2 3; 5 1 4; 3 2 -1]
x =
1 2 3 5 1 4 3 2 -1
transpose y = x’ y =
1 2 5 1
Long Array, Matrix
t =1:10
t =
1 2 3 4 5 6 7 8 9 10
k =2:-0.5:-1
k =
2 1.5 1 0.5 0 -0.5 -1
x = [1:4; 5:8]
x =
1 2 3 4 5 6 7 8
Generating Vectors from functions
zeros(M,N) MxN matrix of zeros
ones(M,N) MxN matrix of ones
rand(M,N) MxN matrix of uniformly
distributed random numbers on (0,1)
x = zeros(1,3) x =
0 0 0 x = ones(1,3) x =
1 1 1
x = rand(1,3) x =
0.9501 0.2311 0.6068
Basic Task: Plot the function sin(x) between 0≤x≤4π
• Create an x-array of 100 samples between 0 and 4π.
• Calculate sin(x) of the x-array
• Plot the y-array
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>plot(y)
0 10 20 30 40 50 60 70 80 90 100
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
Plot the function e
-x/3sin(x) between 0≤x≤4π
Create an x-array of 100 samples between 0 and 4π.
Calculate sin(x) of the x-array
Calculate e-x/3 of the x-array
Multiply the arrays y and y1 wrongly
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>y1=exp(-x/3);
>>y2=y*y1;
Plot the function e
-x/3sin(x) between 0≤x≤4π
Multiply the arrays y and y1 correctly
Plot the y2-array
>>y2=y.*y1;
>>plot(y2)
0 10 20 30 40 50 60 70 80 90 100
-0.3 -0.2 -0.1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7
Display Facilities
plot(.)
stem(.)
Example:
>>x=linspace(0,4*pi,100);
>>y2=y.*y1;
>>plot(y2)
>>plot(x,y2)
Example:
>>stem(y2)
>>stem(x,y2)
0 10 20 30 40 50 60 70 80 90 100
-0.3 -0.2 -0.1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7
0 10 20 30 40 50 60 70 80 90 100
-0.3 -0.2 -0.1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7
Display Facilities
title(.)
xlabel(.)
ylabel(.)
>>title(‘This is the sine function’)
>>xlabel(‘x (secs)’)
>>ylabel(‘sin(x)’)
0 10 20 30 40 50 60 70 80 90 100
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
This is the sinus function
x (secs)
sin(x)
Flow Control
if
for
while
break
….
Control Structures
If Statement Syntax
if (Condition_1)
Matlab Commands elseif (Condition_2)
Matlab Commands elseif (Condition_3)
Matlab Commands else
Matlab Commands end
Some Dummy Examples
if ((a>3) & (b==5))
Some Matlab Commands;
end if (a<3)
Some Matlab Commands;
elseif (b~=5)
Some Matlab Commands;
end if (a<3)
Some Matlab Commands;
else
Some Matlab Commands;
end
Control Structures
For loop syntax
for i=Index_Array Matlab Commands end
Some Dummy Examples
for i=1:100
Some Matlab Commands;
end
for j=1:3:200
Some Matlab Commands;
end
for m=13:-0.2:-21
Some Matlab Commands;
end
for k=[0.1 0.3 -13 12 7 -9.3]
Some Matlab Commands;
end
Control Structures
While Loop Syntax
while (condition)
Matlab Commands end
Dummy Example
while ((a>3) & (b==5))
Some Matlab Commands;
end
Some Useful MATLAB commands
who List known variables
whos List known variables plus their size
help >> help sqrt Help on using sqrt
clear Clear all variables from work space
clear x y Clear variables x and y from work space
clc Clear the command window
MATLAB Help
Ways to get help in MATLAB
help function name
Provides basic text output
Type helpwin on command line
Look under the help menu on the desktop
MATLAB Help
Product help window
Help>product help
Use of M-File
Click to create a new M-File
• Extension “.m”
• A text file containing script or function or program to run
Use of M-File
If you include “;” at the end of each statement, result will not be shown immediately
Save file as Denem430.m
Writing User Defined Functions
Functions are m-files which can be executed by specifying some inputs and supply some desired outputs.
The code telling the Matlab that an m-file is actually a function is
You should write this command at the beginning of the m- file and you should save the m-file with a file name same as the function name
function out1=functionname(in1)
function out1=functionname(in1,in2,in3) function [out1,out2]=functionname(in1,in2)
Notes:
Sometimes slowing down the execution is done
deliberately for observation purposes. You can use the command “pause” for this purpose.
Usually used while plotting
pause %wait until any key pause(3) %wait 3 seconds
Plot
t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t)
grid on
axis square
-1
-0.5
0
0.5
1 -1 -0.5 0 0.5 1
0 5 10 15 20 25 30 35