You are on page 1of 73

MATLAB

Matrix Laboratory
La disciplina
METALIMBAJE

Student Edition MATLAB

Similar cu Versiunea Profesionala


Abilitate de a apela rutine C, C++ si
Fortran
Matrice pana la 16,384 (128 x 128)
elemente
Trei toolbox-uri: Procesare Simnal,
Sisteme de Control si Mat. Simbolica

Metodologia de rezolvare a
problemei

Formularea clara a problemei


Descriere informatiilor intrare si iesire
(I/O)
Se lucreaza problema cu mana pentru un
caz simplu
Se stabileste algoritmul de aplicare a
metodei numerice
Se dezvolta solutia MATLAB
Se depaneaza si se testeaza
Se intocmeste documentatia

MATLAB Review

MATLAB is a numerical analysis system

Can write programs, but they are not


compiled

Should still use structured programming

Should still use comments

Comments are indicated by % at the


beginning of the line

Program Documentation
Comments!!!

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

Command Window
-- enter commands and data
-- print results
Graphics Window
-- display plots and graphs
Edit Window
-- create and modify m-files

Managing MATLAB Environment

who or whos -- See the current runtime environment


clear -- remove all variables from memory
clc -- clear the command window
clf -- clear the graphics window
save -- save the workspace environment
load -- restore workspace from a disk file
abort -- CTRL-C
help -- help command

Really good help command

MATLAB Syntax

No complicated rules
Perhaps the most important thing to
remember is semicolons (;) at the end of a
line suppress output
Type more on to keep text from leaving
screen too fast
diary filename saves a text record of
session
diary off turns it off

MATLAB

MATLABs basic component is a Vector or Matrix

Even single value variables (Scalars)

All operations are optimized for vector use

Loops run slower in MATLAB than in Fortran


(not a vector operation)
size command gives size of the matrix

Scalars, Vectors, Matrices

MATLAB treat variables as matrices


Matrix (m n) - a set of numbers arranged in rows (m) and columns (n)
Scalar: 1 1 matrix
Row Vector: 1 n matrix
Column Vector: m 1 matrix

A 5.27

B 5.02 2.3 7.21

5.02

C B' 2.3
7.21

3 2

2
4
3
.
2
9
.
5

0.5 1 7.2 2

>> pi
ans =
3.1416
>> size(pi)
ans =
1 1

pi 3.1416

>> a=[1 2 3; 4 5 6]
a=
1 2 3
4 5 6
>> size(a)
ans =
2 3

1 2 3
a

4 5 6
a=

MATLAB Example
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
C

b
x

whos
Name
A
C
b
x
y
z

y
z
Size
2x3
2x1
3x1
1x1
1x1
1x1

Bytes
48
16
24
8
8
8

Class
double
double
double
double
double
double

array
array
array
array
array
array

save
Saving to: matlab.mat

default filename

save matrix1

filename matrix1

Data types

All numbers are double precision

Text is stored as arrays of characters

You dont have to declare the type of data


(defined when running)

MATLAB is case-sensitive!!!

Laura ; LAURA; LAura

Variable Names

Usually, the name is identified with the problem


Variable names may consist of up to 31 characters
Variable names may be alphabetic, digits, and the
underscore character ( _ )
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!!)

Initializing Variables

Explicitly list the values


reads from a data file
uses the colon (:) operator
reads from the keyboard
A = [1; 3; 5; 10];
C = [2 3 5 1; 0 1

B = [1 3 5; -6 4 -1]
(continuation)

1 -2; 3 5 1 -3]
E = [A; 1; A];

F = [C(2,3); A]

Matrix Concatenation
x 1 2 3 ;

z x

y 7

9 4

y 1 2 3 7

9 4

u x ; y 1 2 3
7 9 4
v x y ; y x 1 2 3 7 9 4
7 9 4 1 2 3

Colon Operator

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]

1 2
5
1 0

C
3 2 1

4
0 1

2
0

5
1

F
2 1

4
1

Colon Operator

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

1 0
1

C
3 2 1

4
0 1

1
1 0
E

3 2 1

Colon Operator

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
1
3
0

2
5

0
1
2 1

1
4

3 2
G

0 1

Colon Operator

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]

linspace gives 100 evenly spaced values


x = linspace(1,n)
x = linspace(a,b,n_pts)

Special Matrices
1 0 0

eye( 3) 0 1 0
0 0 1

0 0

zeros(3,2) 0 0
0 0

1 1 1
ones( 3) 1 1 1
1 1 1

1 1 1 1
ones(2,4)

1 1 1 1

Arithmetic Operations
Between Two Scalars
Operation
addition
subtraction
multipliat ion
division
exponentiation

Algebraic Form
ab
ab
ab
a
b
b
a

Example: x = (a + b*c)/d^2
count = count + 1

MATLAB
ab
ab
a* b
a/b
a^ b

Precedence of
Arithmetic Operations
1

Parentheses innermost first

exponentiation, left to right

multiplication and division, left to right

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

An array operation is performed


element-by-element
C(1) A(1) * B(1);
C(2) A(2) * B(2);
C(3) A(3) * B(3);
C(4) A(4) * B(4);
C(5) A(5) * B(5);
MATLAB: C = A.*B;

Element-by-Element Operations
Operation
addition
subtraction
multipliat ion
division
exponentiation

Algebraic Form
ab
ab
ab
a
b
b
a

MATLAB
ab
ab
a .* b
a. / b
a .^ b

Array Operation

Vector and Matrix operations


1

a 3
5

b 4
6

ab 7
11

But a*b gives an error (undefined) because


dimensions are incorrect. Need to use .*

1* 2
2

a .* b 3 * 4 12
5 * 6
30

Vectorized Matrix Operations


A 2 3 8 1
B 1 4 5

C A .* B 2 12 40

D A . / B 2 0.75 1.6 0.5


E A .^ 3 8 27

512 1

F ( 3 ).^ B 3 81 243 9

Array Operations for


M N Matrices

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

10

15

20

B A .* 5 5 10 15 20
15
5
10
5

1
8
27
64
C A .^ 3 1 8 27 64
27
1
8
1

Matrix Transpose

x 4 2 3 ;

x'

2
3

y 3 1 2

y'

3
1

- 2

4
4 8
12
x'* y 2 3 1 2 6 2
4
3
9
3 6
3
x * y' 4 2 3 1 ( 4 )( 3 ) ( 2 )( 1 ) 3( 2 ) 4
- 2

Data Files

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

ASCII files
-- in ASCII characters
-- useful if the data is to be shared (imported or
exported to other programs)

MATLAB Input
To read files in

if the file is an ascii table, use load


if the file is ascii but not a table, file I/O needs
fopen and fclose
Reading in data from file using fopen depends
on type of data (binary or text)
Default data type is binary

Save Files

8-digit text format (variable list)


save <fname> <vlist> - ascii
16-digit text format
save <fname> <vlist> - double
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

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

Load Files

Create an ASCII file temp.dat


% Time
0.0
0.5
1.0
1.5
2.0
2.5

Temperature
75.0
73.2
72.6
74.8
79.3
83.2

read Time and Temperature from temp.dat


>> load temp.dat
>> temp

MATLAB Output

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)

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


MATLAB Command Display
Example
format short
default
3.1416
format long
14 decimals 3.14159265358979
format bank
format short e
format long e
format

2 decimals
4 decimals
15 decimals
, , blank

3.14
3.1416e 00
3.141592653589793e 00

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 %08.2f degrees F.\n, temp);


The temperature is 00098.60 degrees F.
fprintf(The temperature is %8.3e degrees F.\n, temp);
The temperature is 9.860e+001 degrees F.

fprintf( ) of
Matrices
Score = [1 2 3 4; 75 88 102 93; 99 84 95 105]
fprintf(Game %1.0f score: Houston: %3.0f Dallas: %3.0f \n,Score)

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

Built-in Functions

All the standard operators +, -, *, /, ^


sin( ), cos( ), exp( ), tanh( ), log( ),
log10( ), etc.
These operators are vectorized

3
a 5 ;
4

sin(3)
exp(3)
sin( a ) sin(5) ; exp(a) exp(5)
sin(4)
exp(4)

Common Program Structures

Sequence
Selection
Repetition

Selection (if) Statements

The most common form of selection


structure is simple if statement
The if statement will have a condition
associated with it
The condition is typically a logical
expression that must be evaluated as
either true or false
The outcome of the evaluation will
determine the next step performed

Logical IF Statements

If (condition) executable_statements
end

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

y
1

-1

Relation Operators

MATLAB
==
~=
<
<=
>
>=
&
|
~

Interpretation
is equal to
is not equal to
is less than
is less than or equal to
is greater than
is greater than or equal to
and, true if both are true
or, true if either one is true
not

Logical Operators

0 - 1 matrix
0: false ; 1: True

a 2 4 6

b 3 5 1

ab

ans 1 1 0

a ~ b

ans 1 1 1

a b&b c

ans 1 0 0

a b | b c

ans 1 1 0

c 4 3 2

Nested IF Statement
if (condition)
statement block
elseif (condition)
another statement block
else
another statement block
end

How to use Nested IF

If the condition is true the


statements following the statement
block are executed.
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 IF Statements

nested if (if, if else, if elseif)


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

y
1

-1

Do loops
Repetition
for i=1:m
for j=1:n
a(i,j)=(i+1)^2*sin(0.2*j*pi);
end
end

Use script file for all do loops

For Loops

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

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

One of the best things about MATLAB is


interactive graphics

plot is the one you will be using most often

Many other 3D plotting functions -- plot3,


mesh, surfc, etc.

Use help plot for plotting options

To get a new figure, use figure

logarithmic plots available using semilogx,


semilogy and loglog

Plotting Commands
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:)
hold on
plot(a,c,ko)

(red dotted line)


(black circles)

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

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)
M-file is an ASCII text file similar to FORTRAN
or C source codes ( computer programs)
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

Plotting Commands
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 or figure (#) : open a figure
figure (2)
plot (x, y, 'r o -'); grid on (red, circle, solid line)
hold on
(blue, star, dotted line)
plot (x, z, 'b * :')

Graphics Commands

Axis, Labels, and Title


xlabel ( label ) ylabel ( label )
title ( title of the plot )
text ( x_location, y_location, text )
axis ( [ x_min x_max y_min y_max ] )
xlabel ( Time )
- text string
ylabel ( Temperature )
title ( Temperature Record : 1900 - 2000 )
text (17, 120, Record High )
text (85, -40, Record Low )
axis ([0 100 -50 140])
hold off

MATLAB Example

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

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

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

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 Integral


f(x)
b

ba
a f ( x)dx 2 f (a) f (b)

area
a

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)

Functions

One variable
function y = function_name(input arguments)
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

my_func.m

function y = my_func(x)
% function 1/x^3
y = x.^(-3);

function q = basic_trap(f, a, b)
% basic trapezoid rule
basic_trap.m ya = feval(f, a);
yb = feval(f, b);
q = (b - a)* (ya + yb)/2;
y = basic_trap ('my_func', 1,3)
y=
1.0370

Approximate the integral of f(x) = 1/x3


using basic trapezoid rule

1
dx
3
x

Filename: trap_ex.m
function t = trap_ex(a, b)
t = (b - a) * (a^(-3) + b^(-3)) / 2;
y = trap_ex (1, 3)
y=
1.0370

Composite Trapezoid Rule


Filename: comp_trap.m
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;

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