8/7/2019 LAB 01 Intro to Matlab
1/26
Control Systems
INTRODUCTION TO MATLAB
LAB# 01
8/7/2019 LAB 01 Intro to Matlab
2/26
Introduction to Matlab
What is Matlab?
Matlab is a commercial MATrix LABoratory package by
Mathworks, which operates as an interactive programming
environment with graphical output.
The MATLAB programming language is exceptionally straight
forward since almost every data object is assumed to be an Array.
In engineering MATLAB is displacing popular programminglanguages, due to its interactive interface, reliable algorithmic
foundation, fully extensible environment and availability of
different tool boxes.
8/7/2019 LAB 01 Intro to Matlab
3/26
Introduction to MATLAB
Entering and Running MATLAB
On a system running Microsoft Windows double click on the
Matlab icon to launch Matlab.
A command window will appear with the prompt >> you are now
in MATLAB.
Leaving Matlab
A MATLAB session may be terminated by simply typing
>> quit or by typing >>exit at the MATLAB prompt.
Online HelpOnline help is available from the MATLAB prompt both generally and
for specific commands.
>> help
>> help demo
8/7/2019 LAB 01 Intro to Matlab
4/26
Desktop Tools (Matlab v7)
Command Window
type commands
Workspace
view program variables clear to clear
double click on a variable to see it in the Array Editor
Command History
view past commands
save a whole session using diary
8/7/2019 LAB 01 Intro to Matlab
5/26
Variables
MATLAB is case sensitive, that is
a is not the same as A
MATLAB has built in variables like pi, eps and ans.
The variable ans will keep track of the last output which was not
assigned to another variable.
Variable Assignment:
The equality sign is used to assigned values to variables.
>> x = 3 y = x ^ 2
Out put can be suppressed by appending a semicolon to thecommand lines.
>> x = 3 ; y = x 2 ;
8/7/2019 LAB 01 Intro to Matlab
6/26
Variables
Active Variables:
Who
Removing Variables Clear x
Clear
Saving and RestoringVariables
Save filename
Load filename
8/7/2019 LAB 01 Intro to Matlab
7/26
Variable Arithmetic
Operator precedence
2 + 3 *4 ^ 2
Double Precision Arithmetic Normally the results will be displayed in a shorter form.
a = sqrt( 2 ) >> a = 1.4142
Format long
b = sqrt ( 2 ) >> b = 1.41421356.
Format short
Command Line Editing
The arrow keys allow command line editing
8/7/2019 LAB 01 Intro to Matlab
8/26
Built in Mathematical Functions
Functions Meaning Examples
Sin sine sin ( pi )=0.0
Cos cosine cos ( pi )=1.0
Tan tangent tan ( pi / 4)=1.0
Exp exponential exp(1.0)=2.7183
log natural log log(2.7183)=1.0
Arguments to trigonometric functions are given in radians.
x= pi / 3; sin( x ) 2 + cos ( x ) ^ 2 = ?
8/7/2019 LAB 01 Intro to Matlab
9/26
Matrices
The element within a row of a matrix may be separated by a commas
as well as a blank.
The elements of a matrix being created are enclosed by brackets.
A matrix is entered in row major order [i.e. all of the first row, then
all of the second row; etc];
Rows are separated by semicolon [or a new line], and the elements of
the row may be separated by either a comma or space.
The following commands will create a 3 x 3 matrix and assigned it to
the variable A.
>> A = [1 2 3; 4 5 6; 7 8 9]; or A = [1,2,3;4,5,6;7,8,9]
>> A = [ 1 2 3
4 5 6
7 8 9 ]
8/7/2019 LAB 01 Intro to Matlab
10/26
Matrices
The matrix element located in the i-th row and j-th column
of A is referred to in the usual way:
>> A (1 , 2), A ( 2 , 3)
Matrices can be easily modified:
A ( 2 , 3 ) = 10;
Building Matrices from a Block:
Large matrices can be assembled from smaller matrix blocks i.e.
C = [A;10 11 12];
[A; A; A] [A, A, A]
>> B = [A, zeros(3,2); zeros(2,3), eye( 2 ) ] ?
8/7/2019 LAB 01 Intro to Matlab
11/26
Built in Matrix Functions
Function Description
diag return diagonal M.E as a vector
eye identity matrixmagic magic squares
ones matrix of ones
rand randomly generated matrix
zeros matrix of zeros
8/7/2019 LAB 01 Intro to Matlab
12/26
Built in Matrix Functions
Matrices of Random Entries: >> rand ( 3 )
>> rand ( m , n )
Magic Squares: A magic square is a square matrix which has equal sums along all its rows
and columns. >> magic ( 4 )
Matrix of Ones: >> eye ( m , n )
>> eye ( n )
Matrices of Zeros:
>> zeros ( m , n ) >> zeros ( n )
Diagonal Matrices: >> diag (A)
diag ( diag ( A ) ) ?
8/7/2019 LAB 01 Intro to Matlab
13/26
Matrix Operations
+ Addition
- Subtraction
* Multiplication
^ Power
Transpose
/ Division
* If the sizes of the matrices are incompatible for the matrix
operation, an error message will result.
.* element-by-element mul
./ element-by-element div
.^ element-by-element power
. transpose
8/7/2019 LAB 01 Intro to Matlab
14/26
Matrix Operations
Matrix Transpose: >> A
Matrix Addition / Subtraction:
A + B, A B
Matrix Multiplication;
A * B , B * A.
Round Floating Point Numbers to Integers: >> f = [-.5 .1 .5 ]
round (f)
ceil (f)
floor (f)
sum (f)
prod (f) Matrix Element Level Operations:
The matrix operation of addition and subtraction are already operates onan element by element basis but other operation given above do not.
Matlab has a convention in which a dot in front of the operations is used.
i.e [1 , 2 , 3 , 4 ] . * [ 1 , 2 , 3 , 4 ]
[ 1 , 2 , 3 , 4 ] . 2
8/7/2019 LAB 01 Intro to Matlab
15/26
Operators (relational, logical)
== equal
~= not equal
< less than greater than
>= greater than or equal
& AND
| OR
~ NOT
8/7/2019 LAB 01 Intro to Matlab
16/26
Branching Constructs
If end Construct:
if < condition >,
< program >
end
If - else - end Construct:
if < condition 1 >,
< program 1>
else
< program2 >
end
If - elseif - end Construct:
if < condition1 >,
< program 1>
elseif
< program2 >
end
8/7/2019 LAB 01 Intro to Matlab
17/26
Looping Constructs
For Loops:
for i = 1 : n ,
< program>,
end
While Loops:
while < condition >,
< program >,
end
Nested For Loops:
for i = 1 : n ,
for j = 1 : n ,
A(i,j) = i/j ;
end
end
8/7/2019 LAB 01 Intro to Matlab
18/26
Matlab M-files
Matlab commands can be run from one file without having
to enter each command one by one at Matlab prompt.
In order to use the programs later in Matlab they are to be
saved first. For this purpose programs should be written in the editor /
debugger.
In command window go to File menu, new and select M-file.
Code your algorithm
Execute it from the command window by typing file name
8/7/2019 LAB 01 Intro to Matlab
19/26
Matlab User Defined Function
Matlab User Defined Function can have an input and output.
Arguments can be passed to a function for computation
For this purpose programs should be written in the editor / debugger.
In command window go to File menu, new and select M-file. function add
x = 3; y = 5;
z = x + y
Save the file and write add at the command prompt
function addv (x,y)
Z = x + y
Save the file and write addv(5,6) at the command prompt
% is used for commenting in front of a statement
8/7/2019 LAB 01 Intro to Matlab
20/26
Input/ Output
Request User Input
data=input(message);
data=input(message,s)
Ouput Data
disp(message)
disp(variable_name)
8/7/2019 LAB 01 Intro to Matlab
21/26
Matlab Graphics
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the
Sine Function')
8/7/2019 LAB 01 Intro to Matlab
22/26
Multiple Graphs
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2)
grid on
8/7/2019 LAB 01 Intro to Matlab
23/26
Multiple Graphs
x = 0 : .01 : 2 * pi;
y1= sin(x);
y2 =sin(2*x);
y3 = sin(4*x);
plot(x,y1,--',x,y2,-,x,y3,+')
grid
title('Dashedlineanddotted
linegraph')
8/7/2019 LAB 01 Intro to Matlab
24/26
Multiple Plots
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
subplot(2,2,1)
plot(t,y1)
subplot(2,2,2)
plot(t,y2)
8/7/2019 LAB 01 Intro to Matlab
25/26
Three Dimensional Graphics
x = -1:.1:1;
y = -1:.1:1;
fori=1:1:length(x)
for j=1:1:length(y)
z(i,j)=x(i)^2+y(j)^2;
end
end
mesh(z);
8/7/2019 LAB 01 Intro to Matlab
26/26
Graph Functions (summary)
plot (x,y) linear plot
plot (x,y1,x,y2) multiple plots on the same graph
mesh(z) 3-D graph
stem (x) discrete plot
xlabel (X-axis label ) add X-axis label
ylabel (Y-axis label ) add Y-axis label
title (title of plot) add graph title
subplot (m,n,p) divide figure window
grid add grid lines
hold hold current graph in the figure
zoom allow zoom in/out using mouse
figure create new figure window
pause wait for user response