You are on page 1of 73

MATLAB

Matrix Laboratory
La disciplina
METALIMBAJE

Student Edition MATLAB
n Similar cu Versiunea Profesionala
n Abilitate de a apela rutine C, C++ si
Fortran
n Matrice pana la 16,384 (128 x 128)
elemente
n Trei toolbox-uri: Procesare Simnal,
Sisteme de Control si Mat. Simbolica
Metodologia de rezolvare a
problemei
n Formularea clara a problemei
n Descriere informatiilor intrare si iesire
(I/O)
n Se lucreaza problema cu mana pentru un
caz simplu
n Se stabileste algoritmul de aplicare a
metodei numerice
n Se dezvolta solutia MATLAB
n Se depaneaza si se testeaza
n Se intocmeste documentatia
MATLAB Review
n MATLAB is a numerical analysis system
n Can write programs, but they are not
compiled
n Should still use structured programming
n Should still use comments
n Comments are indicated by % at the
beginning of the line

Comments!!!
Program Documentation
n You must include comments in the
computer programs you turn in --
otherwise we will have great difficulty
knowing what you are doing
For example, here is some cryptic
code without comment
for j=0:2
k=(2-j)*(1+3*j)/2
end
What does it do?
Put a comment in
% turns (0,1,2) into (1,2,0)
MATLAB Windows
n Command Window
-- enter commands and data
-- print results
n Graphics Window
-- display plots and graphs
n Edit Window
-- create and modify m-files

Managing MATLAB Environment
n who or whos -- See the current runtime environment
n clear -- remove all variables from memory
n clc -- clear the command window
n clf -- clear the graphics window
n save -- save the workspace environment
n load -- restore workspace from a disk file
n abort -- CTRL-C
n help -- help command
Really good help command
MATLAB Syntax
n No complicated rules
n Perhaps the most important thing to
remember is semicolons (;) at the end of
a line suppress output
n Type more on to keep text from
leaving screen too fast
n diary filename saves a text record of
session
n diary off turns it off
MATLAB
n MATLABs basic component is a Vector or
Matrix
n Even single value variables (Scalars)
n All operations are optimized for vector use
n Loops run slower in MATLAB than in
Fortran (not a vector operation)
n size command gives size of the matrix

Scalars, Vectors, Matrices
n MATLAB treat variables as matrices
n Matrix (m n) - a set of numbers arranged in
rows (m) and columns (n)
n Scalar: 1 1 matrix
n Row Vector: 1 n matrix
n Column Vector: m 1 matrix
(
(
(




=
(
(
(

= =
= =
2 2 7 1 5 0
5 9 2 3 4 2
5 2 3 1

21 7
3 2
02 5
21 7 3 2 02 5 27 5
. .
. . D
.
.
.
' B C
. . . B . A
>> pi
ans =
3.1416

>> size(pi)
ans =
1 1

>> a=[1 2 3; 4 5 6]
a =
1 2 3
4 5 6

>> size(a)
ans =
2 3
a=
1416 3. pi =
6 5 4
3 2 1
a
x=3+5-0.2
x =
7.8000
y=3*x^2+5
y =
187.5200
z=x*sqrt(y)
z =
106.8116
A=[1 2 3; 4 5 6]
A =
1 2 3
4 5 6
b=[3;2;5]
b =
3
2
5
C=A*b
C =
22
52
who

Your variables are:

A b y
C x z

whos
Name Size Bytes Class

A 2x3 48 double array
C 2x1 16 double array
b 3x1 24 double array
x 1x1 8 double array
y 1x1 8 double array
z 1x1 8 double array

save

Saving to: matlab.mat

save matrix1
MATLAB Example
default filename
filename matrix1
Data types
n All numbers are double precision
n Text is stored as arrays of characters
n You dont have to declare the type of data
(defined when running)
n MATLAB is case-sensitive!!!
n Laura ; LAURA; LAura

Variable Names
n Usually, the name is identified with the problem
n Variable names may consist of up to 31 characters
n Variable names may be alphabetic, digits, and the
underscore character ( _ )
n Variable names must start with a letter
ABC, A1, C56, CVEN_302
day, year, iteration, max
time, velocity, distance, area, density, pressure
Time, TIME, time (case sensitive!!)
I nitializing Variables
n Explicitly list the values
n reads from a data file
n uses the colon (:) operator
n reads from the keyboard
A = [1; 3; 5; 10]; B = [1 3 5; -6 4 -1]
C = [2 3 5 1; 0 1 (continuation)
1 -2; 3 5 1 -3]
E = [A; 1; A]; F = [C(2,3); A]
Matrix Concatenation
4 9 7 y ; 3 2 1 x = =
4 9 7 3 2 1 y x z = =
3 2 1 4 9 7
4 9 7 3 2 1 x y ; y x v = =
4 9 7
3 2 1 y ; x u = =
Colon Operator
n Creating new matrices from an existing matrix
C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4]
F = C(:, 2:3) = [2,5; 0,1; 2,-1; 1,4]
(
(
(
(

=
(
(
(
(

=
4 1
1 2
1 0
5 2
F
4 1 0
1 2 3
1 0 1
5 2 1
C
Colon Operator
n Creating new matrices from an existing matrix
C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4]
E = C(2:3,:) = [-1 0 1; 3 2 -1]
(

=
(
(
(
(

=
1 2 3
1 0 1
E
4 1 0
1 2 3
1 0 1
5 2 1
C
Colon Operator
n Creating new matrices from an existing matrix
C = [1,2,5; -1,0,1; 3,2,-1; 0,1,4]
G = C(3:4,1:2) = [3,2; 0,1]
(

=
(
(
(
(

=
1 0
2 3
G
4 1 0
1 2 3
1 0 1
5 2 1
C
Colon Operator
n Variable_name = a:step:b
time = 0.0:0.5:2.5
time = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5]
values = 10:-1:2
values = [10, 9, 8, 7, 6, 5, 4, 3, 2]

n linspace gives 100 evenly spaced values
n x = linspace(1,n)
n x = linspace(a,b,n_pts)
Special Matrices
(

=
(
(
(

=
(
(
(

=
(
(
(

=
1 1 1 1
1 1 1 1
ones(2,4)
1 1 1
1 1 1
1 1 1
) 3 ( ones
0 0
0 0
0 0
zeros(3,2)
1 0 0
0 1 0
0 0 1
) 3 ( eye
Arithmetic Operations
Between Two Scalars
b ^ a a tion exponentia
b / a
b
a
division
b * a b a ion multipliat
b a b a n subtractio
b a b a addition
MATLAB Form Algebraic Operation
b


+ +
Example: x = (a + b*c)/d^2
count = count + 1
Precedence of
Arithmetic Operations
1 Parentheses innermost first
2 exponentiation, left to right
3 multiplication and division, left to right
4 addition and subtraction, left to right
Examples: factor = 1 + b/v + c/v^2
slope = (y2 - y1)/(x2 - x1)
loss = f * length/dia * (1/2 * rho * v^2)
func = 1 + 0.5*(3*x^4 + (x + 2/x)^2)
Array Operations
n An array operation is performed
element-by-element
B(5); * A(5) C(5)
B(4); * A(4) C(4)
B(3); * A(3) C(3)
B(2); * A(2) C(2)
B(1); * A(1) C(1)
=
=
=
=
=
MATLAB: C = A.*B;
b .^ a a tion exponentia
b / . a
b
a
division
b .* a b a ion multipliat
b a b a n subtractio
b a b a addition
MATLAB Form Algebraic Operation
b


+ +
Element-by-Element Operations
Array Operation
But a*b gives an error (undefined) because
dimensions are incorrect. Need to use .*
Vector and Matrix operations
(
(
(

= +
(
(
(

=
(
(
(

=
11
7
3
b a
6
4
2
b
5
3
1
a
(
(
(

=
(
(
(

=
30
12
2
6 * 5
4 * 3
2 * 1
b .* a
Vectorized Matrix Operations
9 243 81 3 B ).^ 3 ( F
1 512 27 8 3 .^ A E
5 . 0 6 . 1 75 . 0 2 B / . A D
2 40 12 2 B .* A C
2 5 4 1 B
1 8 3 2 A
= =
= =
= =
= =
=
=
Array Operations for
M N Matrices
(
(
(

= =
5 10 5 15
20 15 10 5
20 15 10 5
5 .* A B
| |
(
(
(

= =
1 2 1 3
4 3 2 1
4 3 2 1
1 - 2 1 3 -4; : -1 : 1 - 4; : 1 A
(
(
(

= =
1 8 1 27
64 27 8 1
64 27 8 1
3 .^ A C
Matrix Transpose
| | | |
| |
| | 4 ) 2 ( 3 ) 1 )( 2 ( ) 3 )( 4 (
2 -
1
3
3 2 4 ' y * x
6 3 9
4 2 6
8 4 12
2 1 3
3
2
4
y '* x
2 -
1
3
y' ;
3
2
4
' x
2 1 3 y ; 3 2 4 x
= + + =
(
(
(

=
(
(
(



=
(
(
(

=
(
(
(

=
(
(
(

=
= =
Data Files
n MAT Files
-- memory efficient binary format
-- preferable for internal use by MATLAB program

n ASCII files
-- in ASCII characters
-- useful if the data is to be shared (imported or
exported to other programs)
MATLAB I nput
To read files in
n if the file is an ascii table, use load
n if the file is ascii but not a table, file I/O
needs fopen and fclose
n Reading in data from file using fopen
depends on type of data (binary or text)
n Default data type is binary
Save Files
n 8-digit text format (variable list)
save <fname> <vlist> - ascii
n 16-digit text format
save <fname> <vlist> - double
n Delimit elements with tabs
save <fname> <vlist> - double - tabs
Example: Vel = [1 3 5; -6 2 -3]
save velocity.dat Vel -ascii

1.0000000e+000 3.0000000e+000 5.0000000e+000
-6.0000000e+000 2.0000000e+000 -3.0000000e+000
Load Files
n Read velocity into a matrix velocity.dat
>> load velocity.dat
>> velocity
velocity = 1 3 5
-6 2 -3

1.0000000e+000 3.0000000e+000 5.0000000e+000
-6.0000000e+000 2.0000000e+000 -3.0000000e+000
n Create an ASCII file temp.dat






n read Time and Temperature from temp.dat
>> load temp.dat
>> temp
% Time Temperature
0.0 75.0
0.5 73.2
1.0 72.6
1.5 74.8
2.0 79.3
2.5 83.2
Load Files
Matlab automatically prints the results of any
calculation (unless suppressed by semicolon ;)
Use disp to print out text to screen
disp (x.*y)
disp (Temperature =)
sprintf - display combination
Make a string to print to the screen
output = sprintf(Pi is equal to %f , pi)

MATLAB Output
Formatted Output
fprintf (format-string, var, .)
%[flags] [width] [.precision] type
Examples of type fields
%e display in exponential notation
%f display in fixed point or decimal notation
%g display using %e or %f, depending on which
is shorter
%% display %
Numeric Display Format
+ + +
+
+
blank , , format
00 e 89793 1415926535 . 3 decimals 15 e long format
00 e 1416 . 3 decimals 4 e short format
14 . 3 decimals 2 bank format
8979 1415926535 . 3 decimals 14 long format
1416 . 3 default short format
Example Display Command MATLAB
x = [5 -2 3 0 1 -2]; format +
x = [+ - + + -] (+/- sign only)
fprintf( ) of Scalar
temp = 98.6;
fprintf(The temperature is %8.1f degrees F.\n, temp);
The temperature is 98.6 degrees F.
fprintf(The temperature is %8.3e degrees F.\n, temp);
The temperature is 9.860e+001 degrees F.
fprintf(The temperature is %08.2f degrees F.\n, temp);
The temperature is 00098.60 degrees F.
fprintf( ) of Matrices
Score = [1 2 3 4; 75 88 102 93; 99 84 95 105]

Game 1 score: Houston: 75 Dallas: 99
Game 2 score: Houston: 88 Dallas: 84
Game 3 score: Houston: 102 Dallas: 95
Game 4 score: Houston: 93 Dallas: 105
fprintf(Game %1.0f score: Houston: %3.0f Dallas: %3.0f \n,Score)
Built-in Functions
n All the standard operators +, -, *, /, ^
n sin( ), cos( ), exp( ), tanh( ), log( ),
log10( ), etc.
n These operators are vectorized

(
(
(

=
(
(
(

=
(
(
(

=
exp(4)
exp(5)
exp(3)
exp(a) ;
sin(4)
sin(5)
sin(3)
) a sin( ;
4
5
3
a
Common Program Structures
n Sequence
n Selection
n Repetition
Selection (if) Statements
n The most common form of selection
structure is simple if statement
n The if statement will have a
condition associated with it
n The condition is typically a logical
expression that must be evaluated as
either true or false
n The outcome of the evaluation will
determine the next step performed
Logical I F Statements
n If (condition) executable_statements
end
-1
1
x
1
y

if (x < = -1.0 | x > = 1.0) y = 0.
end
if (x > -1.0 & x < 0.) y = 1. + x
end
if (x > = 0. & x < 1.0) y = 1.- x
end
Relation Operators
n MATLAB
n ==
n ~=
n <
n <=
n >
n >=
n &
n |
n ~
n Interpretation
n is equal to
n is not equal to
n is less than
n is less than or equal to
n is greater than
n is greater than or equal to
n and, true if both are true
n or, true if either one is true
n not
Logical Operators
n 0 - 1 matrix
n 0: false ; 1: True
0 1 1 ans c b | b a
0 0 1 ans c b & b a
1 1 1 ans b ~ a
0 1 1 ans b a
2 3 4 c 1 5 3 b 6 4 2 a
= >= <=
= < <
= =
= <
= = =
Nested I F Statement
if (condition)
statement block
elseif (condition)
another statement block
else
another statement block
end
How to use Nested I F
n If the condition is true the
statements following the statement
block are executed.
n If the condition is not true, then the
control is transferred to the next
else, elseif, or end statement at the
same if level.
Else and Elseif
if temperature > 100
disp(Too hot - equipment malfunctioning.)
elseif temperature > 75
disp(Normal operating range.)
elseif temperature > 60
disp(Temperature below desired operating range.)
else
disp(Too Cold - turn off equipment.)
end
Nested I F Statements
n nested if (if, if else, if elseif)
-1
1
x
1
y

if (x < = -1.0)
y = 0.
elseif (x < = 0.)
y = 1. + x
elseif (x < = 1.0)
y = 1. - x
else
y=0.
end
Repetition

for i=1:m
for j=1:n
a(i,j)=(i+1)^2*sin(0.2*j*pi);
end
end
Do loops
Use script file for all do loops
For Loops
n for index = expression
statements
end
for k = 1:length(d)
if d(k) < 30
velocity(k) = 0.5 - 0.3*d(k).^2;
else
velocity(k) = 0.6 + 0.2*d(k)-0.01*d(k).^2
end
end
While Loops
n while index = expression
statements
end
If the statement is true, the statements are executed
If the statement is always true, the loop becomes an
infinite loop
The break statement can be used to terminate the
while or for loop prematurely.
MATLAB Graphics
n One of the best things about MATLAB is
interactive graphics
n plot is the one you will be using most often
n Many other 3D plotting functions -- plot3,
mesh, surfc, etc.
n Use help plot for plotting options
n To get a new figure, use figure
n logarithmic plots available using semilogx,
semilogy and loglog
plot(x,y) defaults to a blue line
plot(x,y,ro) uses red circles
plot(x,y,m*) uses magenta asterisks
If you want to put two plots on the same
graph, use hold on
plot(a,b,r:) (red dotted line)
hold on
plot(a,c,ko) (black circles)
Plotting Commands
x=0:0.1:5;
y=2*x.^3-12*x.^2+8*x-6;
H=plot(x,y,'b',x,y,'r*');
set(H,'LineWidth',3,'MarkerSize',12)
xlabel('x'); ylabel('y');
title('f(x)=2x^3-12x^2+8x-6');
print -djpeg075 poly.jpg
element-by-element
operations x.^n
x=0:0.1:10;
y=sin(2.*pi*x)+cos(pi*x);
H1=plot(x,y,'m'); set(H1,'LineWidth',3); hold on;
H2=plot(x,y,'bO'); set(H2,'LineWidth',3,'MarkerSize',10); hold off;
xlabel('x'); ylabel('y');
title('y = sin(2*pi*x)+cos(pi*x)');
print -djpeg075 function.jpg
x=0:0.1:3; y1=exp(-x); y2=sqrt(x);
H=plot(x,y1,'b-',x,y2,'r--');
set(H,'LineWidth',3)
xlabel('x'); ylabel('y'); title('MATLAB Plots');
H1=text(1.8,0.2,'exp(-x)'); set(H1,'FontSize',18);
H2=text(1.8,1.3,'sqrt(x)'); set(H2,'FontSize',18);
M-Files: Scripts and Functions
n You can create and save code in text files using
MATLAB Editor/Debugger or other text editors
(called m-files since the ending must be .m)
n M-file is an ASCII text file similar to FORTRAN
or C source codes ( computer programs)
n A script can be executed by typing the file name,
or using the run command
Difference between scripts and functions
Scripts share variables with the main workspace
Functions do not
plot (x, y) plot(x1, y1, x2, y2)
plot (x, y, color symbol line style)
x = linspace(0, 2*pi);
y = sin (2.*x);
z = cos (0.5*x);
plot (x, y)
plot (x, y, x, z)
figure (2)
plot (x, y, 'r o -'); grid on
hold on
plot (x, z, 'b * :')
(red, circle, solid line)
(blue, star, dotted line)
figure or figure (#) : open a figure
Plotting Commands
xlabel ('Time')
ylabel ('Temperature')
title ('Temperature Record : 1900 - 2000')
text (17, 120, 'Record High' )
text (85, -40, 'Record Low' )
axis ([0 100 -50 140])
hold off
xlabel (' label ') ylabel (' label ')
title (' title of the plot ')
text ( x_location, y_location, ' text ' )
axis ( [ x_min x_max y_min y_max ] )
' ' - text string
Graphics Commands
n Axis, Labels, and Title
MATLAB Example
n Filename waves.m (script file)
% Plot Bi-chromatic Wave Profile
a1 = 1; a2 = 1.5; c1 = 2.0; c2 = 1.8;
time = 0:0.1:100;
wave1 = a1 * sin(c1*time);
wave2 = a2 * sin(c2*time) + a1;
wave3 = wave1 + wave2;
plot(time,wave1,time,wave2,time,wave3)
axis([0 100 -2 4]);
xlabel ('time'); ylabel ('wave elevation');
title ('Bi-chromatic Wave Profile')
text(42,-1.2, 'wave 1')
text(42, 2.7, 'wave 2')
text(59, 3.6, 'waves 1+2')
MATLAB Subplots
n Filename waves2.m (script file)
% Plot Bi-chromatic Wave Profile
% Display the results in three subplots
clf % clear the graphics window
a1 = 1; a2 = 1.5; c1 = 2.0; c2 = 1.8;
time = 0:0.1:100;
wave1 = a1 * sin(c1*time);
wave2 = a2 * sin(c2*time);
wave3 = wave1 + wave2;
subplot(3,1,1) % top figure
plot(time,wave1,'m'); axis([0 100 -3 3]); ylabel('wave 1');
subplot(3,1,2) % middle figure
plot(time,wave2,'g'); axis([0 100 -3 3]); ylabel('wave 2');
subplot(3,1,3) % bottom figure
plot(time,wave3,'r'); axis([0 100 -3 3]);
xlabel(time'); ylabel('waves 1&2');
subplot ( m, n, p ) --
breaks the figure window into m by n small figures,
select the p-th figure for the current plot
figure (3)
subplot (3, 2, 1)
plot (t,wv1)
subplot (3, 2, 2)
plot (t,wv2)
subplot (3, 2, 4)
plot (t, wv1+wv2)
subplot (3, 2, 6)
plot (t, wv1-wv2)
MATLAB Subplots
1 2
3 4
5 6
x=0:0.1:10; y1=sin(pi*x); y2=sin(0.5*pi*x); y3=y1+y2;
z1=cos(pi*x); z2=cos(0.5*pi*x); z3=z1-z2;
subplot(3,2,1); H1=plot(x,y1,'b'); set(H1,'LineWidth',2);
subplot(3,2,2); H2=plot(x,z1,'b'); set(H2,'LineWidth',2);
subplot(3,2,3); H3=plot(x,y2,'m'); set(H3,'LineWidth',2);
subplot(3,2,4); H4=plot(x,z2,'m'); set(H4,'LineWidth',2);
subplot(3,2,5); H5=plot(x,y3,'r'); set(H5,'LineWidth',2);
subplot(3,2,6); H6=plot(x,z3,'r'); set(H6,'LineWidth',2);
Subplot (m,n,p)
Multiple plots
Script File for I ntegral
1. Save integral (f, a, b) in script file integral.m
2. Save function my_func(x) in script my_func.m
3. Run script file
>> area = integral(my_func, 1, 10)
>> area = integral(my_func, 3, 6)
| | ) b ( f ) a ( f
2
a b
dx ) x ( f
b
a
+

=
area
a b
f(x)
x
Functions
n One variable
function y = function_name(input arguments)
n More than one output variables
function [y, z] = function_name(input arguments)
Examples: function y = my_func (x)
y = x^3 + 3*x^2 -5 * x +2 ;

function area = integral (f, a, b)
ya = feval (f, a); yb = feval(f, b);
area = (b-a)*(ya+yb)/2;
feval - evaluate function specified by string
function y = my_func(x)
% function 1/x^3
y = x.^(-3);
function q = basic_trap(f, a, b)
% basic trapezoid rule
ya = feval(f, a);
yb = feval(f, b);
q = (b - a)* (ya + yb)/2;
my_func.m
basic_trap.m
y = basic_trap ('my_func', 1,3)
y =
1.0370
function t = trap_ex(a, b)
t = (b - a) * (a^(-3) + b^(-3)) / 2;
Approximate the integral of f(x) = 1/x
3

using basic trapezoid rule
Filename: trap_ex.m
y = trap_ex (1, 3)
y =
1.0370

dx
x
1
y
b
a
3
=
Composite Trapezoid Rule
function I = Trap(f, a, b, n)
% find the integral of f using
% composite trapezoid rule
h=(b - a)/n; S = feval(f, a);
for i = 1 : n-1
x(i) = a + h*i;
S = S + 2*feval(f, x(i));
end
S = S + feval(f, b); I =h*S/2;
Filename: comp_trap.m
x
f
a b
Composite Trapezoid Rule
I=comp_trap('my_func',1,3,1)
I =
1.0370
I=comp_trap('my_func',1,3,2)
I =
0.6435
I=comp_trap('my_func',1,3,4)
I =
0.5019
I=comp_trap('my_func',1,3,8)
I =
0.4596
I=comp_trap('my_func',1,3,16)
I =
0.4483
I=comp_trap('my_func',1,3,100)
I =
0.4445
I=comp_trap('my_func',1,3,500)
I =
0.4444
I=comp_trap('my_func',1,3,1000)
I =
0.4444
one segment
two segments
four segments
eight segments
16 segments
100 segments
500 segments
1000 segments

You might also like