Você está na página 1de 125

MATLAB

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

MATLAB User Environment

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)

Linux (Environment network)


MATLAB installed in /apps/matlab
Your code in /home/username/matlab
Your environment configuration in ~/.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

Use startup.m for setting paths, forcing


preferred settings, etc.
Matlab Basics

Example startup.m file (for my laptop)


%------------------------------------% Matlab startup file for IMB's laptop
%------------------------------------%-- add paths for my m-files -addpath d:/matlab
addpath d:/matlab/bulk2.5
addpath d:/matlab/bulk2.6
addpath d:/matlab/coastal
addpath d:/matlab/lidar
addpath d:/matlab/ndbc
addpath d:/matlab/page
addpath d:/matlab/sections
addpath d:/matlab/sharem
addpath d:/matlab/wavelet
addpath d:/matlab/LEM
addpath d:/matlab/GPSbook
addpath d:/matlab/FAAM
addpath d:/matlab/FAAM/winds
addpath d:/matlab/faam/bae
%-- add netCDF toolbox -addpath c:/matlab701/bin
addpath c:/matlab701/bin/win32
addpath d:/matlab/netcdf
addpath d:/matlab/netcdf/ncfiles
addpath d:/matlab/netcdf/nctype
addpath d:/matlab/netcdf/ncutility

%-- add path for generic data -addpath d:/matlab/coastlines

% coastline data

addpath d:/cw96/flight_data/jun02 % raw cw96


addpath d:/cw96/flight_data/jun07 % aircraft data
addpath d:/cw96/flight_data/jun11
addpath d:/cw96/flight_data/jun12
addpath d:/cw96/flight_data/jun17
addpath d:/cw96/flight_data/jun19
addpath d:/cw96/flight_data/jun21
addpath d:/cw96/flight_data/jun23
addpath d:/cw96/flight_data/jun26
addpath d:/cw96/flight_data/jun29
addpath d:/cw96/flight_data/jul01
addpath d:/cw96/runs % run definitions for cw96 flights
%---------------------------------------------------------------------%-- set default figure options -set(0,'DefaultFigurePaperType','a4')
% this should be the default in EU anyway
set(0,'DefaultFigurePaperUnits','inches')
% v6 defaults to cm for EU countries
set(0,'DefaultFigureRenderer','painters')
% v7 default OpenGL causes problems

Matlab Basics

addpath adds directories to


the search path. MATLAB will
look in ALL directories on the
path for:
Functions and scripts (.m files)
MATLAB data files (.mat files)

The set commands in the


example startup.m file set
some default graphics
properties, overriding the
defaults will cover these
later.

It will also look in the current


directory

Matlab Basics

MATLAB Basics: Variables


Variables:
-Variables are assigned numerical values by
typing the expression directly
>> a = 1+2
>> a =
3

press enter

>> a = 1+2;

suppresses the output


Matlab Basics

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

3x2 matrix 6 elements

b=[1 2 3 4]

1x4 array 4 elements, row vector

1
c= 3
5

3x1 array 3 elements, column vector

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;

; semicolon suppresses the


automatic echoing of values but
it slows down the execution.

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

Never change the values of predefined variables.

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

parentheses (starting from the innermost)


exponentials (from left to right)
multiplications and divisions (from left to right)
additions and subtractions (from left to right)

>> 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

help elfun help for elementary math functions


CS 111

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

Use shorter statements


Check typos
Check units
Ask your friends, assistants, instructor,
39

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

Few methods to create vector


LINSPACE(x1, x2): generates a row vector of 100
linearly equally spaced points between x1 and x2.
LINSPACE(x1, x2, N): generates N points between x1
and x2.
LOGSPACE(d1, d2): generates a row vector of 50
logarithmically equally spaced points between decades
10^d1 and 10^d2.
a = 0:2:10 generates a row vector of 6 equally spaced
points between 0 and 10.
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

Example: Draw sine wave

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

Example: Discrete time signal

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

Example: Draw unit step and


delayed unit step functions

n=input('enter value of n')


t=0:1:n-1;
y1=ones(1,n); %unit step
y2=[zeros(1,4) ones(1,n-4)]; %delayed unit step
subplot(2,1,1);
stem(t,y1,'filled');ylabel('amplitude');
xlabel('n----->');ylabel('amplitude');
subplot(2,1,2);
stem(t,y2,'filled');
xlabel('n----->');ylabel('amplitude');
Matlab Basics

Matlab Plot

Matlab Basics

Functions

Matlab Basics

Scripts and Functions


Script files are M-files with some valid MATLAB
commands.
Generally work on global variables present in the
workspace.
Results obtained after executing script files are
left in the workspace.

Matlab Basics

Scripts and Functions


Function files are also M-files but with local
variables .
Syntax of defining a function
function [output variable] = function_name (input
variable)
File name should be exactly same as function
name.
Matlab Basics

Example : user defined function


Assignment is the method of giving a value to a variable.
You have already seen this in the interactive mode. We
write x=a to give the value of a to the value of x. Here is
a short program illustrating the use of assignment.
function r=mod(a,d)
%If a and d are integers, then r is the integer remainder of a after division by d.
If a and b are integer matrices, then r is the matrix of remainders after
division by corresponding entries.

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

a =[10 10 10]; d = [3 3 3];


mod(a,d);

Another .m file to access


above function
Matlab Basics

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

Few in-built Matlab functions


sin()
cos()
log()
asin()
acos()
exp()
sinh()

sqrt()
square()
rand()
random()
real(x)
imag(x)
conv()

Type help, followed by the function name on the


Matlab command window, press enter. This will
display the function definition.
Study the definition of each function.
Matlab Basics

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

whos : lists names and basic properties of variables in the workspace


>> whos
Name
x
y

Size

Bytes

3x1
3x2

24
48

Class
double array
double array

Grand total is 9 elements using 72 bytes

pwd, cd, dir, ls : similar to operating system (but no option switches)


>> pwd
ans =
D:\
>> cd cw96\jun02
>> dir
.
30m_wtv.mat

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]

When defining variables, a space or


comma separates elements on a
row.

A newline or semicolon forces a


new row; these 2 statements are
equivalent.
NB. you can break definitions across
multiple lines.

x =
1
2
3
4
Matlab Basics

1 & 2D arrays are treated as formal matrices


Matrix algebra works by default:
1x2 row oriented array (vector)
(Trailing semicolon suppresses display of output)

>> a=[1 2];


>> b=[3
4];

2x1 column oriented array

>> a*b
ans =
11
Result of matrix multiplication depends on
order of terms (non-cummutative)

>> b*a
ans =
3
4

6
8
Matlab Basics

Element-by-element operation is forced by


preceding operator with .
>> a=[1 2];
>> b=[3
4];
>> a.*b
??? Error using ==> times
Matrix dimensions must agree.

Matlab Basics

Size and shape must match

>> a=[1 2]
A =
1

No trailing semicolon,
immediate display of result
2

>> b=[3 4];


>> a.*b
ans =
3
>> c=a+b
c =
4

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

Most common functions operate on


columns by default

Matlab Basics

INDEXING ARRAYS
n
m

MATLAB indexes arrays:

IDL indexes arrays:

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

The colon indicates a range, a:b (a to b)

>> A(2,:)
ans =
4

A colon on its own indicates ALL values


5

6
Matlab Basics

THE COLON OPERATOR


Colon operator occurs in several forms
To indicate a range (as above)
To indicate a range with non-unit increment
>> N = 5:10:35
N =
5

15

25

35

>> P = [1:3; 30:-10:10]


P =
1

30

20

10

Matlab Basics

To extract ALL the elements of an array (extracts


everything to a single column vector)
>> A = [1:3; 10:10:30;
100:100:300]
A =
1
10
100

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

By default save overwrites an existing file of the same


name, the append switch forces appending data to
an existing file (but variables of same name will be
overwritten!)
save var1 var2 filename -append
Matlab Basics

Data is recovered with the load command


load filename loads entire .mat file
load filename var1 var2 loads named variables
load filename ascii loads contents of an ascii
flatfile in a variable filename.
The ascii file must contain a rectangular array of numbers so
that it loads into a single matrix.
X=load(filename,-ascii) loads the ascii file into
a variable X
save var1 filename ascii saves a single variable
to an ascii flat file (rectangular array of numbers)
Matlab Basics

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

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

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)

You can also pass the function parts of a matrix


>> function_Name(matrix(:, 1))
or
>> function_Name(matrix(:, 2:4))

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

This will display information on how to use the


function and what it does

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)

When using std, max and min you need to write:


>> 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)

Can now be written


>> results(:, 5) = sum(results(:, 1:4), 2)
or
>> results(:, 5) = prod(results(:, 1:4), 2)

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.-)

In the last example the line style is defined


Colour: r, b, g, c, k, y etc.
Point style: . + * x o > etc.
Line style: - -- : .-

Type help plot for a full list of the options

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:

hold on and hold off


title
legend
axis
xlabel
ylabel

102

5 Plotting
>> x = [0:0.1:2*pi];
>> y = sin(x);

>> plot(x, y*2, r.-')

0.5
y

>> title('Sin Plots');

>> axis([0 6.2 -2 2])

0
-0.5

>> xlabel(x);

-1

>> ylabel(y);

-1.5

>> hold off

sin(x)
2*sin(x)

1.5

>> hold on

>> legend('sin(x)', '2*sin(x)');

Sin Plots

>> plot(x, y, 'b*-')

-2

3
x

103

5 Plotting
Plotting data
0.9
0.8
0.7
0.6
0.5

>> results = rand(10, 3)


>> plot(results, 'b*')
>> hold on
>> plot(mean(results, 2), r.-)

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

Introduction of using MATLAB


with test and
measurement instruments

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?

What can we do with MATLAB?


Why does MATLAB attract many peoples attentions in
both industries and academia?
Numerical computing environment and programming language.
Easy matrix manipulation, plotting of functions and data, implementation of
algorithms, creation of user interfaces, and interfacing with programs in other
languages (e.g., C).
Over 1,000,000 users in diverse industries and disciplines up to end of 2007.
It becomes a standard at more than 3,500 colleges and universities worldwide.

What can we do with MATLAB?

What can we do with MATLAB?

There are still a lot of functionalities and built-in toolboxes of


MATLAB which can be explored and applied to aid our research.

The common toolboxes which might be essential and useful:


Signal Processing Toolbox (Filter and window signals, estimate spectral
response, generate custom waveforms, etc.)
Image Processing Toolbox (Transform, register, filter, enhance, restore, and
analyse images, etc.)
Statistic Toolbox (Compute descriptive statistics from test results, etc.)
Curve Fitting Toolbox (given by Min)
System Identification Toolbox (Develop and simulate linear models from
measured time-series or frequency-domain data, etc.)
Neural Network Toolbox (Develop nonlinear system models, etc.)
Instrument Control Toolbox (How can this be used?)

How can we make good use of Instrument Control


Toolbox built in MATLAB to meet your needs?

The Instrument Control Toolbox lets you


communicate with instruments, such as
oscilloscopes, function generators, and
analytical instruments, directly from MATLAB [1].

Selected key features:

Instrument driver support for IVI, VXIplug&play, and


MATALB instrument drivers.
Support for GPIB and VISA standard protocols.
Support for networked instruments using the TCP/IP
and UDP protocols.
Graphical user interface for identifying, configuring,
and communicating with instruments.
Instrument driver development and testing tools.
Sending commands and writing data to instruments.
Recording of data transferred to and from instruments.

How can we make good use of Instrument Control


Toolbox built in MATLAB to meet your needs?

The Instrument Control Toolbox provides a variety of ways to


communicate with instruments, including:

Instrument drivers
Communication protocols
Graphical user interface (TMTool)
Simulink Blocks

How can we make good use of Instrument Control


Toolbox built in MATLAB to meet your needs?
The Instrument Control Toolbox
provides a variety of ways to
communicate with instruments,
including:
Instrument drivers
Using the instrument drivers is
probably the most straightforward way
to communicate with an instrument
independent of device protocol.
You can use common MATLAB
terminology to communicate with
instruments without learning
instrument-specific commands, such
as Standard Commands for
Programmable Instrument (SCPI).
Requirements: VXIplug&play, IVI, and
MATLAB instrument drivers. [1]

How can we make good use of Instrument Control


Toolbox built in MATLAB to meet your needs?

The Instrument Control Toolbox provides a variety of ways to


communicate with instruments, including:
Communication protocols
The toolbox supports communication protocols, i.e., GPIB, serial, TCP/IP,
and UDP, for directly communicating with instruments.
We can also communicate with instruments using VISA [1] over GPIB, VXI,
USB, TCP/IP, and serial buses.
The toolbox provides a set of M-file functions for creating and working with
instruments.
These available functions let you write commands to the instruments or read
data from your instruments for use in MATLAB.
The toolbox supports the text commands used by the instruments, such as
SCPI. [2] The transferred data can be binary or ASCII.

How can we make good use of Instrument Control


Toolbox built in MATLAB to meet your needs?
The Instrument Control Toolbox
provides a variety of ways to
communicate with instruments,
including:
Graphical user interface (TMTool)
Test and Measurement Tool (built
in Instrument Control Toolbox) is
a GUI that enables programmers
and nonprogrammers to
implement following tasks:

Search for available hardware


Connect to an instrument
Configure instrument settings
Write data to an instrument
Read data from an instrument

How can we make good use of Instrument Control


Toolbox built in MATLAB to meet your needs?

The Instrument Control Toolbox provides a variety of ways to


communicate with instruments, including:
Simulink Blocks
The Instrument Control Toolbox also includes instrument control blocks for
use with Simulink.
Blocks are provided for sending live data from Simulink model to an
instrument, and for querying an instrument to receive live data into your
model.
This needs to be explored further and deeper?~!@#$%^&

Demos

Examples of using GPIB communication protocol to communicate


with the Agilent Signal Generator (ESG series):
GPIB (HPIB or IEEE-488) is a standardized interface that allows you to connect and
control devices from various vendors. The Standard Commands for Programmable
Instrumentation (SCPI) specification builds on the commands given by the IEEE 488.2
specification to define a standard instrument command set that can be used by GPIB
or other interfaces.
Common commands[1]:

*CLS (Clear Status);


*ESE (Standard Event Status Enable);
*IDN? (Identification query);
*RST (Reset);
etc. (More information refer to Programming Guide: Agilent Technologies ESG Family Signal
Generators)

Generate predefined RF waveforms.

Demos

Examples of using VISA standard for communicating with Anritsu


Spectrum Analyser regardless of the interfaces.
The Instrument Control Toolboxs VISA object supports seven communication
interface types: serial, GPIB, GPIB-VXI, VXI, TCPIP, USB, and RSIB.
The communication bus between the PC and the Anritsu Spectrum Analyser is
Ethernet cable. Therefore, I used the VISA standard over TCPIP interface to set up
the communications between these.
The codes look like this:

Demos

The complete test and measurement instrument network.


Sends
commands

PC

Agilent
Signal Generator
Connectors

MATLAB

Anritsu
Fetches
measured data

Post-processing

Spectrum Analyser

RF Signals

Demos

Quick demos of using Test and Measurement Tool (GUI interface)


built in Instrument Control Toolbox for communicating with
instruments.
It provides you an alternative and visual way for driving your instruments
in MATLAB.
It allows you work back to generate the M-file for further and finer
modification of commands.
It is probably the good start point for new users of the Instrument
Control Toolbox.

Conclusion

The importance and influence of MATLAB.

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.

Some useful links:

The help documents which are detailed in MATLAB;


Instrument Control Toolbox online resources:
www.mathworks.com/products/instrument/;
Drivers, and examples of using MATLAB with instruments from different vendors:
http://www.mathworks.com/products/instrument/supportedio.html.

Question time?

Você também pode gostar