1
Introduction to Matlab-2
Laboratoire Mathématiques, Informatique et Applications
2
Desktop Tools (Matlab v6)
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
Launch Pad– access tools, demos and documentation
3
Matlab Files (.m)
Use predefined functions or write your own functions
Reside on the current directory or the search path– add with File/Set Path
Use the Editor/Debugger to edit, run
4
Matrices
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
5
Matrices
x(i,j) subscription
whole row
whole column
y=x(2,3)
y =
4
y=x(3,:)
y =
3 2 -1
y=x(:,2)
y =
2
1
2
6
Operators (arithmetic)
+addition- subtraction* multiplication/ division^power‘ complex
conjugate transpose
.* element-by-element mult
./ element-by-element div
.^ element-by-element power
.‘ transpose
7
Operators (relational, logical)
== equal~= not equal< less than<= less than or equal> greater than>= greater than or
equal
& AND| OR~ NOT
1
pi 3.14159265…
j imaginary unit,
i same as j
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
9
Operators
[ ] concatenation
( ) subscription
x = [ zeros(1,3) ones(1,2) ]x = 0 0 0 1 1
x = [ 1 3 5 7 9]x = 1 3 5 7 9
y = x(2)y = 3y = x(2:4)y = 3 5 7
10
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');
11
Multiple Graphs
t =0:pi/100:2*pi;y1=sin(t);y2=sin(t+pi/2);plot(t,y1,t,y2);grid on;
12
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);
13
If Statements
IF expression statements ELSEIF expression statements ELSE statements END
14
Example clear all; close all; n=10; x=1:n; y=zeros([1,n]); for k=1:n
y(k) = 2*k; end
plot(x,y);
15
Homework
Generate a tree structure for the system equation y=sin(ax) + bx knowing that x is the system input and y is the system output. X and y are arrays of n values. Assume n = 100;
Generate a random sequence from -2 to 2 to be used as the system input x using the randn command.
Plot the input versus the output of the above system.
16
Solution
clear all;close all;
x=2-4*rand(1,100);a=2;b=3;
y=sin(a*x) + b*x;
subplot(2,1,1); plot(x); grid;title('system input');subplot(2,1,2); plot(y,'r'); grid;title('system output');
17
18
Graph Functions (summary)
plot linear plot grid add grid lines xlabel add X-axis label ylabel add Y-axis label title add graph title subplot divide figure window figure create new figure window pause wait for user response
19
Math Functions
Elementary functions (sin, cos, sqrt, abs, exp, log10, round)– type help elfun
Advanced functions (bessel, beta, gamma, erf)– type help specfun– type help elmat
20
Scripts
Matlab editor Use scripts to execute a series of
Matlab commands
Matlab Desktop
Press to create new m-file in the matlab editor
21
Functions
function f=myfunction(x,y)f=x+y;
save it in myfunction.m call it with y=myfunction(x,y)
22
Functions Programming in Matlab. Users can write functions which can be called from the
command line. Functions can accept input variable(s)/matrice(s) and
will output variable(s)/matrice(s). Functions will not manipulate variable(s)/matrice(s) in
the Matlab Workspace. In Matlab functions closely resemble scripts and can be
written in the Matlab editor. Matlab functions have the function keyword.
Remember that the filename of a function will be its calling function name.
Don’t overload any built-in functions by using the same filename for your functions or scripts!
Functions can be opened for editing using the open command. Many built-in Matlab functions can also be viewed using this command.
23
>> I=iterate(5)I = 1 4 9 16 25
Functions (continued)
outputinputfunction name
for statement block
function keyword
help lines for function
Access the comments of your Matlab functions >> help iterate Make sure you save changes to the
m-file before you call the function!
24
>> [i j]=sort2(2,4)i = 4j = 2>>
Functions (continued)
Functions can have many outputs contained in a matrix
Remember to use the Matlab help command for syntax>> help if
if statement block
25
More flow control
Method is linear>>
i =
4
i =
16
i =
256
While statement block Switch statement block
Without ; to print output
26
Debugging
Set breakpoints to stop the execution of code>> [i j]=sort2(2,4)K>> K>> whos Name Size Bytes Class a 1x1 8 double array b 1x1 8 double arrayGrand total is 2 elements using 16 bytesK>> aa = 2K>> returni =
4j = 2
Click mouse on the left of the line of code to create a breakpoint
local function workspace
exit debug mode
Debug menus
27
Visualisation - plotting data
>> figure % create new figure>> t=0:pi/12:8*pi;>> y=cos(t);>> plot(t,y,‘b.-')
Investigate the function >> y=A*cos(w*t+phi);for different values of phi (eg: 0, pi/4, pi/3, pi/2), w (eg: 1, 2, 3, 4) and A (eg: 1, 0.5, 2). Use the hold on Matlab command to display your plots in the same figure. Remember to type hold off to go back to normal plotting mode. Try using different plot styles (help plot) A = amplitude
phi = phasew = angular frequency = 2*pi*frequency
Plot style
28
Flow Control
A=3; B=2;if A > B
'greater'elseif A < B
'less'else
'equal'end
for x = 1:10r(x) = x;
end
• if statement• switch statement
• for loops• while loops
• continue statement• break statement
29
Miscellaneous
Loading data from a file– load myfile.dat
Definition – x = [1 2 5 1];
30
Getting Help
Using the Help Browser (.html, .pdf)– View getstart.pdf, graphg.pdf, using_ml.pdf
Type – help – help function, e.g. help plot
Running demos – type demos– type help demos
31
>> help stem
STEM Discrete sequence or "stem" plot. STEM(Y) plots the data sequence Y as stems from the x
axisterminated with circles for the data value. STEM(X,Y) plots the data sequence Y at the values specified in
X. STEM(...,'filled') produces a stem plot with filled markers. STEM(...,'LINESPEC') uses the linetype specified for the stems
and markers. See PLOT for possibilities. H = STEM(...) returns a vector of line handles. See also PLOT, BAR, STAIRS.
32
Random Numbers
x=rand(100,1);stem(x);
hist(x,100)
33
Coin Tosses
Simulate the outcomes of 100 fair coin tosses
x=rand(100,1);p=sum(x<0.5)/100
p = 0.5400
Simulate the outcomes of 1000 fair coin tosses
x=rand(1000,1);p=sum(x<0.5)/1000
p = 0.5110
34
Coin Tosses
Simulate the outcomes of 1000 biased coin tosses with p[Head]=0.4
x=rand(1000,1);p=sum(x<0.4)/1000
p = 0.4160
35
Sum of Two Dies
Simulate 10000 observations of the sum of two fair dies
.
.
.
.
.
. . . . .
.
. . . .. .
... .
.
..
.
.
...
.. .. .. .
(1,1) (2,1) (3,1) (4,1) (5,1) (6,1)
(3,2) (4,2) (5,2) (6,2)
(3,3) (4,3) (5,3) (6,3)
(2,2)(1,2)
(2,3)(1,3)
(1,4) (2,4) (3,4) (4,4) (5,4) (6,4)
(3,5) (4,5) (5,5) (6,5)(2,5)(1,5)
(3,6) (4,6) (5,6) (6,6)(2,6)(1,6)
1 2 3 4 5 6
1
2
3
4
5
6
36
Sum of Two Dies
for i=2:12z(i)=sum(y==i)/10000
endbar(z)
Boolean Operations
» x=[0 1 1]; y=[1 1 1];» and(x,y)» ans =» 0 1 1» or(x,y)» ans =» 1 1 1
» x=[0 1 1]; y=[1 1 1];» and(x,y)» ans =» 0 1 1» or(x,y)» ans =» 1 1 1
Boolean Operators
= = equal to
> greater than
< less than
~ not
& and
| or
isempty()
isfinite(), etc. . . .
any()
all()
1 = TRUE0 = FALSE
»bool_ops
Solving Simultaneous Equationsusing “Left Division”
If [A] is square matrix (m = n):
For overdetermined system (m>n): using Least squares regression “curve fit” of data
Warning if rank deficient (dependent columns) - solution not unique
For undetermined system (m<n): using QR factorization with column pivoting
Never unique
[A]{x} = {b} {x} = ?
{x} = [A]-1{b}» x = inv(A)*b;
» x = A\b;
» x = inv(A)*b;
» x = A\b;
Error if singularWarning if nearly singular
[A] = mxn{x} = nx1{b} = mx1
» x = A\b;» x = A\b;
» x = A\b;» x = A\b;
Solve this set of simultaneous equations:
Example: Solving Equations
» A = [-1 1 2; 3 -1 1;-1 3 4];
» b = [2;6;4];
» x = inv(A)*b
x =
1.0000
-1.0000
2.0000
» x = A\b
x =
1.0000
-1.0000
2.0000
» A = [-1 1 2; 3 -1 1;-1 3 4];
» b = [2;6;4];
» x = inv(A)*b
x =
1.0000
-1.0000
2.0000
» x = A\b
x =
1.0000
-1.0000
2.0000
-x1 + x2 + 2x3 = 2
3x1 - x2 + x3 = 6
-x1 + 3x2 + 4x3 = 4
40
Return to our example
clear all;close all;n=20;x=rand(1,n);x1= [0 x(1:n-1)];x2= [0 0 x(1:n-2)];a=2;b=5;y= a*x1 + b*x2;figure; plot(y,'r'); grid;title('system output');
String Arrays
Created using single quote delimiter (')
Each character is a separate matrix element (16 bits of memory per character)
Indexing same as for numeric arrays
» str = 'Hi there,'
str =
Hi there,
» str2 = 'Isn''t MATLAB great?'
str2 =
Isn't MATLAB great?
» str = 'Hi there,'
str =
Hi there,
» str2 = 'Isn''t MATLAB great?'
str2 =
Isn't MATLAB great?
1x9 vectorstr = H i t h e r e ,
» str ='Hi there,';
» str1='Everyone!';
» new_str=[str, ' ', str1]
new_str =Hi there, Everyone! » str2 = 'Isn''t MATLAB great?';
» new_str2=[new_str; str2]new_str2 =Hi there, Everyone!Isn't MATLAB great?
» str ='Hi there,';
» str1='Everyone!';
» new_str=[str, ' ', str1]
new_str =Hi there, Everyone! » str2 = 'Isn''t MATLAB great?';
» new_str2=[new_str; str2]new_str2 =Hi there, Everyone!Isn't MATLAB great?
1x19 vector
1x9 vectors
String Array Concatenation
Using [ ] operator:Each row must be same length
Row separator:semicolon (;)
Column separator:space / comma (,)For strings of different
length:•STRVCAT•STR2MAT
» new_str3 = strvcat(str, str2)new_str3 =Hi there, Isn't MATLAB great?
» new_str3 = strvcat(str, str2)new_str3 =Hi there, Isn't MATLAB great?
2x19 matrix
2x19 matrix(zero padded)
1x19 vectors
Working with String Arrays
String Comparisons– STRCMP - compare whole strings– STRNCMP - compare first ‘N’ characters– FINDSTR - finds substring within a larger string
Converting between numeric & string arrays:– NUM2STR - convert from numeric to string array– STR2NUM - convert from string to numeric array
44
End of Lecture