Escolar Documentos
Profissional Documentos
Cultura Documentos
Basics
Matlab Basics
Introduction
MATLAB -> MATrix LABoratory
Built-in Functions
-Computations
-Graphics
-External Interface
-Optional Toolbox for Signal Processing,
System analysis, Image Processing
Matlab Basics
Workspace/Variable
Inspector
Command Window
Command History
Matlab Basics
MATLAB Windows
Command window: main window characterized
by >> command prompt.
Edit window: where programs are written and
saved as M-files.
Graphics window: shows figures, alternately
known as Figure window.
Matlab Basics
Getting help
There are several ways of getting help:
Basic help on named commands/functions is echoed to the command
window by:
>> help command-name
A complete help system containing full text of manuals is started by:
>> helpdesk
Matlab Basics
System Environment
Windows
MATLAB installed in c:\matlab\
Your codeanywhere convenient (e.g. h:\matlab)
Matlab Basics
startup.m
The script $matlab_root\toolbox\local\matlabrc.m
is always run at startup it reads system
environment variables etc, and initialises
platform dependent settings. If present it will run
a user defined initialisation script: startup.m
Linux: /home/user/matlab/startup.m
Windows: $matlab_root\toolbox\local\startup.m
% coastline data
Matlab Basics
Matlab Basics
press enter
>> a = 1+2;
Variables
several predefined variables
i sqrt(-1)
j sqrt(-1)
pi 3.1416...
>> y= 2*(1+4*j)
>> y=
2.0000 + 8.0000i
Matlab Basics
Variables
Global Variables
Local Variables
Matlab Basics
MATLAB BASICS
Variables and Arrays
Array: A collection of data values organized into rows
and columns, and known by a single name.
Row 1
Row 2
Row 3
arr(3,2)
Row 4
Col 1 Col 2 Col 3 Col 4 Col 5
CS 111
13
MATLAB BASICS
Arrays
The fundamental unit of data in MATLAB
Scalars are also treated as arrays by MATLAB (1
row and 1 column).
Row and column indices of an array start from 1.
Arrays can be classified as vectors and
matrices.
CS 111
14
MATLAB BASICS
Vector: Array with one dimension
Matrix: Array with more than one dimension
Size of an array is specified by the number of rows
and the number of columns, with the number of
rows mentioned first (For example: n x m array).
Total number of elements in an array is the
product of the number of rows and the number of
columns.
CS 111
15
MATLAB BASICS
1 2
a= 3 4
5 6
b=[1 2 3 4]
1
c= 3
5
a(2,1)=3
Row #
CS 111
b(3)=3
c(2)=3
Column #
16
MATLAB BASICS
Variables
A region of memory containing an array, which is known
by a user-specified name.
Contents can be used or modified at any time.
Variable names must begin with a letter, followed by any
combination of letters, numbers and the underscore (_)
character. Only the first 31 characters are significant.
The MATLAB language is Case Sensitive. NAME, name
and Name are all different variables.
Give meaningful (descriptive and easy-to-remember)
names for the variables. Never define a variable with the
same name as a MATLAB function or command.
CS 111
17
MATLAB BASICS
Common types of MATLAB variables
double: 64-bit double-precision floating-point numbers
They can hold real, imaginary or complex numbers in the
range from 10-308 to 10308 with 15 or 16 decimal digits.
>> var = 1 + i ;
char: 16-bit values, each representing a single character
The char arrays are used to hold character strings.
>> comment = This is a character string ;
The type of data assigned to a variable determines the
type of variable that is created.
CS 111
18
MATLAB BASICS
Initializing Variables in Assignment Statements
An assignment statement has the general form
var = expression
Examples:
CS 111
>> var = 40 * i;
>> var2 = var / 5;
>> array = [1 2 3 4];
>> x = 1; y = 2;
>> a = [3.4];
>> b = [1.0 2.0 3.0 4.0];
>> c = [1.0; 2.0; 3.0];
>> d = [1, 2, 3; 4, 5, 6];
>> e = [1, 2, 3
4, 5, 6];
>> a2 = [0 1+8];
>> b2 = [a2(2) 7 a];
>> c2(2,3) = 5;
>> d2 = [1 2];
>> d2(4) = 4;
19
MATLAB BASICS
Initializing Variables in Assignment Statements
Arrays are constructed using brackets and semicolons.
All of the elements of an array are listed in row order.
The values in each row are listed from left to right and
they are separated by blank spaces or commas.
The rows are separated by semicolons or new lines.
The number of elements in every row of an array must be
the same.
The expressions used to initialize arrays can include
algebraic operations and all or portions of previously
defined arrays.
CS 111
20
MATLAB BASICS
Initializing with Shortcut Expressions
first: increment: last
Colon operator: a shortcut notation used to initialize
arrays with thousands of elements
>> x = 1 : 2 : 10;
>> angles = (0.01 : 0.01 : 1) * pi;
Transpose operator: () swaps the rows and columns
of an array
1 1
2 2
>> f = [1:4];
h=
3 3
>> g = 1:4;
4 4
>> h = [ g g ];
CS 111
21
MATLAB BASICS
Initializing with Built-in Functions
zeros(n)
zeros(n,m)
zeros(size(arr))
ones(n)
ones(n,m)
ones(size(arr))
eye(n)
eye(n,m)
>> a = zeros(2);
>> b = zeros(2, 3);
>> c = [1, 2; 3, 4];
>> d = zeros(size(c));
length(arr)
size(arr)
CS 111
22
MATLAB BASICS
Initializing with Keyboard Input
The input function displays a prompt string in the
Command Window and then waits for the user to
respond.
my_val = input( Enter an input value: );
in1 = input( Enter data: );
in2 = input( Enter data: ,`s`);
CS 111
23
MATLAB BASICS
Multidimensional Arrays
A two dimensional array with m rows and n columns
will occupy mxn successive locations in the computers
memory. MATLAB always allocates array elements in
column major order.
a= [1 2 3; 4 5 6; 7 8 9; 10 11 12];
a(5) = a(1,2) = 2
A 2x3x2 array of three dimensions
c(:, :, 1) = [1 2 3; 4 5 6 ];
c(:, :, 2) = [7 8 9; 10 11 12];
1
4
1
10
10 11 12
5
8
11
CS 111
24
MATLAB BASICS
Subarrays
It is possible to select and use subsets of MATLAB
arrays.
arr1 = [1.1 -2.2 3.3 -4.4 5.5];
arr1(3) is 3.3
arr1([1 4]) is the array [1.1 -4.4]
arr1(1 : 2 : 5) is the array [1.1 3.3 5.5]
For two-dimensional arrays, a colon can be used in a
subscript to select all of the values of that subscript.
arr2 = [1 2 3; -2 -3 -4; 3 4 5];
arr2(1, :)
arr2(:, 1:2:3)
CS 111
25
MATLAB BASICS
Subarrays
The end function: When used in an array subscript, it
returns the highest value taken on by that subscript.
arr3 = [1 2 3 4 5 6 7 8];
arr3(5:end) is the array [5 6 7 8]
arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];
arr4(2:end, 2:end)
Using subarrays on the left hand-side of an assignment
statement:
arr4(1:2, [1 4]) = [20 21; 22 23];
(1,1) (1,4) (2,1) and (2,4) are updated.
arr4 = [20 21; 22 23]; all of the array is changed.
CS 111
26
MATLAB BASICS
Subarrays
Assigning a Scalar to a Subarray: A scalar value on the
right-hand side of an assignment statement is copied
into every element specified on the left-hand side.
>> arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];
>> arr4(1:2, 1:2) = 1
arr4 =
1 1 3 4
1 1 7 8
9 10 11 12
CS 111
27
MATLAB BASICS
Special Values
MATLAB includes a number of predefined special values.
These values can be used at any time without initializing
them.
These predefined values are stored in ordinary variables.
They can be overwritten or modified by a user.
If a new value is assigned to one of these variables, then
that new value will replace the default one in all later
calculations.
>> circ1 = 2 * pi * 10;
>> pi = 3;
>> circ2 = 2 * pi * 10;
CS 111
28
MATLAB BASICS
Special Values
pi: value up to 15 significant digits
i, j: sqrt(-1)
Inf: infinity (such as division by 0)
NaN: Not-a-Number (division of zero by zero)
clock: current date and time in the form of a 6-element
row vector containing the year, month, day, hour,
minute, and second
date: current date as a string such as 16-Feb-2004
eps: epsilon is the smallest difference between two
numbers
ans: stores the result of an expression
CS 111
29
MATLAB BASICS
Changing the data format
>> value = 12.345678901234567;
format short
12.3457
format long
12.34567890123457
format short e
1.2346e+001
format long e
1.234567890123457e+001
format short g
12.346
format long g
12.3456789012346
format rat
1000/81
CS 111
30
MATLAB BASICS
The disp( array ) function
>> disp( 'Hello' )
Hello
>> disp(5)
5
>> disp( [ 'Bilkent ' 'University' ] )
Bilkent University
>> name = 'Alper';
>> disp( [ 'Hello ' name ] )
Hello Alper
CS 111
31
MATLAB BASICS
The num2str() and int2str() functions
>> d = [ num2str(16) '-Feb-' num2str(2004) ];
>> disp(d)
16-Feb-2004
>> x = 23.11;
>> disp( [ 'answer = ' num2str(x) ] )
answer = 23.11
>> disp( [ 'answer = ' int2str(x) ] )
answer = 23
CS 111
32
MATLAB BASICS
The fprintf( format, data ) function
%d
%f
%e
%g
\n
\t
CS 111
integer
floating point format
exponential format
either floating point or exponential
format, whichever is shorter
new line character
tab character
33
MATLAB BASICS
>> fprintf( 'Result is %d', 3 )
Result is 3
>> fprintf( 'Area of a circle with radius %d is %f', 3, pi*3^2 )
Area of a circle with radius 3 is 28.274334
>> x = 5;
>> fprintf( 'x = %3d', x )
x= 5
>> x = pi;
>> fprintf( 'x = %0.2f', x )
x = 3.14
>> fprintf( 'x = %6.2f', x )
x = 3.14
>> fprintf( 'x = %d\ny = %d\n', 3, 13 )
x=3
y = 13
CS 111
34
MATLAB BASICS
Data files
save filename var1 var2
>> save myfile.mat x y
binary
>> save myfile.dat x ascii
ascii
load filename
>> load myfile.mat
>> load myfile.dat ascii
CS 111
binary
ascii
35
MATLAB BASICS
variable_name = expression;
CS 111
addition
subtraction
multiplication
division
exponent
a+b
a-b
axb
a/b
ab
a+b
a-b
a*b
a/b
a^b
36
MATLAB BASICS
Hierarchy of operations
x=3*2+6/2
Processing order of operations is important
>> x = 3 * 2 + 6 / 2
x=
9
CS 111
37
MATLAB BASICS
Built-in MATLAB Functions
result = function_name( input );
abs, sign
log, log10, log2
exp
sqrt
sin, cos, tan
asin, acos, atan
max, min
round, floor, ceil, fix
mod, rem
38
MATLAB BASICS
Types of errors in MATLAB programs
Syntax errors
Check spelling and punctuation
Run-time errors
Check input data
Can remove ; or add disp statements
Logical errors
CS 111
MATLAB BASICS
Summary
CS 111
help command
lookfor keyword
which
clear
clc
diary filename
diary on/off
who, whos
more on/off
Ctrl+c
Online help
Lists related commands
Version and location info
Clears the workspace
Clears the command window
Sends output to file
Turns diary on/off
Lists content of the workspace
Enables/disables paged output
Aborts operation
Continuation
Comments
40
MATLAB Basics:
Arithmetic operators:
+ addition,
- subtraction,
* multiplication,
/division,
^ power operator,
' transpose
Matlab Basics
Matrices
Matrices : Basic building block
Elements are entered row-wise
>> v = [1 3 5 7]creates a 1x4 vector
>> M = [1 2 4; 3 6 8] creates a 2x3 matrix
>> M(i,j) => accesses the element of ith row and
jth column
Matlab Basics
Basics Matrices
Special Matrices
null matrix:
M = [];
nxm matrix of zeros: M = zeros(n,m);
nxm matrix of ones: M = ones(n,m);
nxn identity matrix: M = eye(n);
--Try these Matrices
[eye(2);zeros(2)],[eye(2);zeros(3)], [eye(2),ones(2,3)]
Matlab Basics
Matrix Operations
Matrix operations:
A+B is valid if A and B are of same size
A*B is valid if As number of columns equals Bs
number of rows.
A/B is valid and equals A.B-l for same size square
matrices A & B.
Element by element operations:
.* , ./ , .^ etc
--a = [1 2 3], b = [2 2 4],
=>do a.*b and a*b
Matlab Basics
Vectors
Matlab Basics
Waveform representation
Matlab Basics
2D Plotting
plot:
creates linear continuous plots of
vectors and matrices;
plot(t,y): plots the vector t on the x-axis
versus vector y on the y-axis.
To label your axes and give the plot a title, type
xlabel('time (sec)')
ylabel('step response')
title('My Plot')
Change scaling of the axes by using the axis
command after the plotting command:axis([xmin
xmax ymin ymax]);
Matlab Basics
2D Plotting
stem(k,y): for discrete-time signals this
command is used.
To plot more than one graph on the screen,
subplot(m,n,p): breaks the Figure window into an
m-by-n matrix of small axes, selects the p-th
sub-window for the current plot
grid : shows the underlying grid of axes
Matlab Basics
t=-2*pi:0.1:2*pi;
y=1.5*sin(t);
plot(t,y);
xlabel('------> time')
ylabel('------> sin(t)')
Matlab Basics
Matlab Plot
Matlab Basics
t=-2*pi:0.5:2*pi;
y=1.5*sin(t);
stem(t,y);
xlabel('------> time')
ylabel('------> sin(t)')
Matlab Basics
Matlab Plot
Matlab Basics
Matlab Plot
Matlab Basics
Functions
Matlab Basics
Matlab Basics
r=a-d.*floor(a./d);
%You should make a file named mod.m and enter this program exactly as it is
written.
%Now assign some integer values for a and d writing another .m file and Run
Loops, flows:
for m=1:10:100
num = 1/(m + 1)
end
%i is incremented by 10 from 1 to 100
I = 6; j = 21
if I > 5
k = I;
elseif (i>1) & (j == 20)
k = 5*I + j
else
k = 1;
end
%if statement
Matlab Basics
Recapitulate
Matlab Basics
sqrt()
square()
rand()
random()
real(x)
imag(x)
conv()
Practice
1>Draw a straight line satisfying the equation: y = 3*x + 10
2> Create matrices with zeros, eye and ones
3>Draw a circle with radius unity. (use cos for x axis, sin for y axis)
4>Draw a cosine wave with frequency 10kHz. Use both plot and stem
functions to see the difference.
5>Multiply two matrices of sizes 3x3.
6>Plot the parametric curve x(t) = t, y(t) = exp(-t/2) for 0<t<pi/2 using ezplot
7>Plot a cardioid r() = 1 + cos() for 0< <pi/2
Matlab Basics
The WORKSPACE
MATLAB maintains an active workspace, any
variables (data) loaded or defined here are
always available.
Some commands to examine workspace, move
around, etc:
who : lists variables in workspace
>> who
Your variables are:
x
Matlab Basics
Size
Bytes
3x1
3x2
24
48
Class
double array
double array
edson2km.mat
..
edson_2km_bulk.mat
Matlab Basics
960602_sst.mat
jun02_30m_runs.mat
VARIABLES
Everything (almost) is treated as a doubleprecision floating point array by default
Typed variables (integer, float, char,) are supported,
but usually used only for specific applications. Not all
operations are supported for all typed variables.
[IDL uses typed variables, but allows mixing of
types...at least to some extent]
Matlab Basics
>> x=[1 2 3]
x =
1
2
>> x=[1,2,3]
x =
1
2
>> x=[1
2
3
4];
>> x=[1;2;3;4]
x =
1
2
3
4
Matlab Basics
>> a*b
ans =
11
Result of matrix multiplication depends on
order of terms (non-cummutative)
>> b*a
ans =
3
4
6
8
Matlab Basics
Matlab Basics
>> a=[1 2]
A =
1
No trailing semicolon,
immediate display of result
2
Element-by-element
multiplication
8
Matrix addition & subtraction
operate element-by-element
anyway. Dimensions of
matrix must still match!
Matlab Basics
>> A = [1:3;4:6;7:9]
A =
1
2
3
4
5
6
7
8
9
>> mean(A)
ans =
4
5
>> sum(A)
ans =
12
18
15
Matlab Basics
INDEXING ARRAYS
n
m
1 to N
[row,column]
[1,1
2,1
3,1
.
m,1
1,2
2,2
3,2
.
m,2
0 to N-1
[column,row]
.
.
.
.
.
[0,0
1,0
0,1
1,1
0,2
1,2
.
.
0,m-1 1,m-1
1,n
2,n
3,n
m,n]
Matlab Basics
. n-1,0
. n-1,1
. n-1,2
.
.
. n-1,m-1]
>> A = [1:3;4:6;7:9]
A =
1
2
3
4
5
6
7
8
9
>> A(2,3)
ans =
6
>> A(1:3,2)
ans =
2
5
8
>> A(2,:)
ans =
4
6
Matlab Basics
15
25
35
30
20
10
Matlab Basics
2
20
200
3
30
300
>> A(:)
ans =
1
10
100
2
20
200
3
30
300
Matlab Basics
LOGICAL INDEXING
Instead of indexing arrays directly, a logical
mask can be used an array of same size, but
consisting of 1s and 0s usually derived as
result of a logical expression.
>> X = [1:10]
X =
1
10
10
>> ii = X>6
ii =
0
>> X(ii)
ans =
7
Matlab Basics
Basic Operators
+, -, *, / : basic numeric operators
\ : left division (matrix division)
^ : raise to power
: transpose (of matrix) flip along diagonal
fliplr(), flipud() : flip matrix about
vertical and horizontal axes.
Matlab Basics
SAVING DATA
MATLAB uses its own platform independent file format
for saving data files have a .mat extension
The save command saves variables from the
workspace to a named file (or matlab.mat if no
filename given)
save filename saves entire workspace to filename.mat
save var1 var2 filename saves named variables
to filename.mat
Matlab Basics
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
Control Structures
For loop syntax
for i=Index_Array
Matlab Commands
end
Control Structures
While Loop Syntax
while (condition)
Matlab Commands
end
Dummy Example
while ((a>3) & (b==5))
Some Matlab Commands;
end
Matlab Basics
4 Functions
A function performs an operation on the input
variable you pass to it
Passing variables is easy, you just list them within
round brackets when you call the function
function_Name(input)
86
4 Functions
The result of the function can be stored in a variable
>> output_Variable = function_Name(input)
e.g.
>> mresult = mean(results)
You can also tell the function to store the result in parts of
a matrix
>> matrix(:, 5) = function_Name(matrix(:, 1:4))
87
4 Functions
To get help with using a function enter
>> help function_Name
88
4 Functions
MATLAB has many built in functions which make it easy to perform a
variety of statistical operations
sum Sums the content of the variable passed
prod Multiplies the content of the variable passed
mean Calculates the mean of the variable passed
median Calculates the median of the variable passed
mode Calculates the Mode of the variable passed
std Calculates the standard deviation of the variable passed
sqrt Calculates the square root of the variable passed
max Finds the maximum of the data
min Finds the minimum of the data
size Gives the size of the variable passed
89
4 Special functions
There are a number of special functions that provide
useful constants
pi
= 3.14159265.
i or j = square root of -1
Inf
= infinity
NaN
= not a number
4 Functions
Passing a vector to a function like sum, mean, std
will calculate the property within the vector
>> sum([1,2,3,4,5])
= 15
>> mean([1,2,3,4,5])
=3
91
4 Functions
When passing matrices the property, by default, will
be calculated over the columns
92
4 Functions
To change the direction of the calculation to the other
dimension (columns) use:
>> function_Name(input, 2)
93
4 Functions
From Earlier
>> results(:, 5) = results(:, 1) + results(:, 2) + results(:, 3) +
results(:, 4)
or
>> results(:, 5) = results(:, 1) .* results(:, 2) .* results(:, 3) .*
results(:, 4)
94
4 Functions
More usefully you
can now take the
mean and standard
deviation of the
data, and add them
to the array
95
4 Functions
You can find the maximum and minimum of some
data using the max and min functions
>> max(results)
>> min(results)
96
4 Functions
We can use functions and logical indexing to extract all the
results for a subject that fall between 2 standard deviations of
the mean
>> r = results(:,1)
>> ind = (r > mean(r) 2*std(r)) & (r < mean(r) + 2*std(r))
>> r(ind)
97
5 Plotting
98
5 Plotting
The plot function can be used in different ways:
>> plot(data)
>> plot(x, y)
>> plot(data, r.-)
99
5 Plotting
A basic plot
>> x = [0:0.1:2*pi]
>> y = sin(x)
>> plot(x, y, r.-)
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
100
5 Plotting
Plotting a matrix
MATLAB will treat each column as a different set of data
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
10
101
5 Plotting
Some other functions that are helpful to create plots:
102
5 Plotting
>> x = [0:0.1:2*pi];
>> y = sin(x);
0.5
y
0
-0.5
>> xlabel(x);
-1
>> ylabel(y);
-1.5
sin(x)
2*sin(x)
1.5
>> hold on
Sin Plots
-2
3
x
103
5 Plotting
Plotting data
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
10
104
5 Plotting
Error bar plot
>> errorbar(mean(data, 2), std(data, [], 2))
Mean test results with error bars
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
10
12
105
5 Plotting
You can close all the current plots using close all
106
Matlab Basics
Matlab Basics
Overview
What can we do with MATLAB?
How can we make good use of Instrument Control
Toolbox built in MATLAB to meet your needs?
Some techniques and demos of using Instrument
Control Toolbox with test and measurement
instruments.
Conclusion
Questions?
Instrument drivers
Communication protocols
Graphical user interface (TMTool)
Simulink Blocks
Demos
Demos
Demos
PC
Agilent
Signal Generator
Connectors
MATLAB
Anritsu
Fetches
measured data
Post-processing
Spectrum Analyser
RF Signals
Demos
Conclusion
How can we make good use of Instrument Control Toolbox in the practical
test and measurement researches?
Some demos and techniques of applying the Instrument Control Toolbox are
given.
Question time?