Anda di halaman 1dari 41

Breve Introduo

Programao em MATLAB

Aulas Prticas de Aprendizagem Automtica
Ano Lectivo 2006/2007
Susana Nascimento

Departamento de Informtica
snt@di.fct.unl
Introduo MatLab AA-0607 2
Introduo ao MatLab
O ambiente de trabalho das aulas prticas: MATLAB.

O MATLAB um ambiente de programao de alto nvel para
aplicaes Cientficas e de Engenharia.

Facilidades
Oferece um leque alargado de bibliotecas de funes pr-
definidas.

Muito amigvel em funcionalidades grficas para Visualizao de
Dados.

Largamente divulgado em Universidades e Laboratrios de
Investigao.

Muito conveniente para o desenvolvimento efics de prottipos.

Introduo MatLab AA-0607 3
MATLAB the Language
of Technical Computing
Simulink for Model-based and
System-Level Design
Site para Consulta da Linguagem:
http://www.mathworks.com/access/helpdesk/help/techdoc/learn_matlab/learn_matlab.shtml
Introduo MatLab AA-0607 4
Sumrio
Tipos de dados
arrays: caracteres, numricos, estruturados,
Operadores
aritmtica, relacionais, lgicos.
Fluxo de Controlo
condicionais, case, while, etc.
M-functions
sintaxe
Exemplos e funes simples

Introduo MatLab AA-0607 5
Introduo MatLab AA-0607 6
Tipos de Dados em MatLab
Array
Char Numeric Structure Cell
a image.width = 120
image.name = face1
Uint8
(8 bit unsigned integer,
from 0 to 255,
e.g., image gray scales)

Double
e.g., 3.2567
(8 bytes)
Introduo MatLab AA-0607 7
Uint8 e Doubles
Double
Maioria funes MATLAB
doubles como argumento de entrada
return double
Introduo MatLab AA-0607 8
Uint8 e Doubles
Double
Maioria funes MATLAB
doubles como argumento de entrada
return double
e.g.,


Necessidade de converter uint8 para
double antes de realizar operao
matemtica
a = 1:10
a =
1 2 3 4 5 6 7 8 9 10
b = uint8(a)
b =
1 2 3 4 5 6 7 8 9 10
whos
Name Size Bytes Class

a 1x10 80 double array
b 1x10 10 uint8 array

b*2
??? Error using ==> *
Function '*' not defined for variables of class 'uint8'.

(double(b))*2

ans =

2 4 6 8 10 12 14 16 18 20
Introduo MatLab AA-0607 9
Tipo Char
c = ['hello'];
whos
Name Size Bytes Class
c 1x5 10 char array
Grand total is 5 elements using 10 bytes

c(1)
ans =
h

Introduo MatLab AA-0607 10
Tipo de Dados Char
c = ['hello'];
whos
Name Size Bytes Class
c 1x5 10 char array
Grand total is 5 elements using 10 bytes

c(1)
ans =
h

d = [c,' again'];
d
d =
hello again

b = ['hello';'again'];
size(b)
ans =
2 5
b
b =
hello
again


Introduo MatLab AA-0607 11
Tipo de Dados Struct
image.name = 'Tom';
image.height = 3;

image.width = 3;

image.data = [8 10 2; 22 7 22; 2 4 7];

whos
Name Size Bytes Class

image 1x1 590 struct array

Grand total is 18 elements using 590 bytes
Introduo MatLab AA-0607 12
Tipo de dados Arrays de Estruturas
image(1) = image;
image(2).name = 'Mary'
image(2).width = 4;
image(2).height = 4;
whos
Name Size Bytes Class

image 1x2 894 struct array

Grand total is 28 elements using 894 bytes

image

image =

1x2 struct array with fields:
name
height
width
data

Introduo MatLab AA-0607 13
Arrays de Estruturas
image(1) = image;
image(2).name = 'Mary'
image(2).width = 4;
image(2).height = 4;
whos
Name Size Bytes Class

image 1x2 894 struct array

Grand total is 28 elements using 894 bytes

image

image =

1x2 struct array with fields:
name
height
width
data

image(2)

ans =

name: 'Mary'
height: 4
width: 4
data: []

image(1)

ans =

name: 'Tom'
height: 3
width: 3
data: [3x3 double]

Introduo MatLab AA-0607 14
Operadores
Aritmticos
Computao numrica, e.g., 2^10

Relacional
Comparao quantitativa de operandos
e.g., a < b

Lgico
AND, OR, NOT
Devolve varivel Booleana, 1 (TRUE) ou 0 (FALSE)


Introduo MatLab AA-0607 15
Operadores Aritmticos
Transpose, a
Power, a^2
Addition, multiplication, division
a(1)*b(2)
a*b
works if a and b are matrices
with appropriate dimensions
(columns(a) = rows(b))
a.*b (element by element)
except for matrix operations, most
operands must be of the same size,
unless one is a scalar

Introduo MatLab AA-0607 16
Operadores Aritmticos
Transpose, a
Power, a^2
Addition, multiplication, division
a(1)*b(2)
a*b
works if a and b are matrices
with appropriate dimensions
(columns(a) = rows(b))
a.*b (element by element)
except for matrix operations,
operands must be of the same size,
unless one is a scalar

a = [2 3];
b = [4 5];
a(1)*b(2)
ans =
10

a*b
??? Error using ==> *
Inner matrix dimensions must agree.

a*b'
ans =
23

a.*b
ans =

8 15

b/2
ans =
2.0000 2.5000
Introduo MatLab AA-0607 17
Operadores Relacionais
<, <=, >, >=, ==, ~=

compare corresponding elements
of arrays with same dimensions

if one is scalar, one is not, the scalar
is compared with each element

result is, element by element, 1 or 0


Introduo MatLab AA-0607 18
Operadores Relacionais
<, <=, >, >=, ==, ~=

compare corresponding elements
of arrays with same dimensions

if one is scalar, one is not, the scalar
is compared with each element

result is element by element 1 or 0


a
a =
2 3

b
b =
4 5

a > b
ans =
0 0

b > a
ans =
1 1

a > 2
ans =
0 1

Introduo MatLab AA-0607 19
Fluxo de Controlo
If, else, endif
if index<100
statements
else
statements
end
For..
For i = 1:100
statements
end
Switch, while

Introduo MatLab AA-0607 20
Programao em MATLAB
File with MATLAB code: M file, e.g., sort.m
Two kinds of M-files
scripts
no input arguments supplied
no output arguments returned
operates on data in workspace
functions
can accept input arguments and return output arguments
internal variables local to function by default
useful for extending functionality of MATLAB
Introduo MatLab AA-0607 21
Exemplo de Script MATLAB
% script randVect
% Script simples para gerar um vector de n n. aleatrios.
% ilustar aplicando:
% (a) loops for, and (b) chamada directa a uma funo.
%
%





Comentar o cdigo
Introduo MatLab AA-0607 22
Exemplo de Script MATLAB
% script randVect
% Script simples para gerar um vector de n n. aleatrios.
% ilustar aplicando:
% (a) loops for, and (b) chamada directa a uma funo.
%
%

n = 100000; % the number of points for the "for loop
y = zeros(n,1); % preallocate memory for y
fprintf('Simulating %d random numbers.....\n\n',n);






Inicializao de variveis



Print de informao para o ecran
Introduo MatLab AA-0607 23
Exemplo de Script MATLAB
% script randVect
% Script simples para gerar um vector de n n. aleatrios.
% ilustar aplicando:
% (a) loops for, and (b) chamada directa a uma funo.


n = 100000; % the number of points for the "for loop
y = zeros(n,1); % preallocate memory for y
fprintf('Simulating %d random numbers.....\n\n',n);

% first do the calculation using a "for loop"
fprintf('For loop calculations.....\n');
tic % set the timer
for i=1:n
y(i) = rand(1);
end
total = sum(y);
fprintf('Sum of %d random numbers = %f\n',n,total);
t1 = toc; % read the time elapsed since "tic" (in seconds)
fprintf('Time taken, using for loop = %6.5f microseconds\n\n', (t1)*1000);

...
(1) Calcula n n. aleatrios
e correspondente soma usando loop for;
(2) Calcular tempo execuo;
(3) mostrar resultado
Introduo MatLab AA-0607 24
Exemplo de Script MATLAB


% now do the calculation using vectorization
fprintf('Vectorization calculations.....\n');

tic % reset the timer
z = rand(n,1);
total = sum(z);

fprintf('Sum of %d random numbers = %f\n',n,total);
t2 = toc; % read the time elapsed since "tic" (in seconds)
fprintf('Time taken, using vectorization = %6.5f microseconds\n', (t2)*1000);
(1) Calcula n n. aleatrios
e correspondente soma usando funo rand;
(2) Calcular tempo execuo;
(3) mostrar resultado
Introduo MatLab AA-0607 25
Gerador de Nmeros (pseudo)aleatrios
em MatLab
Gera sequncia (of length n) de ns pseudoaleatrios:
Gerao da sequncia: x(i) = mod(a * x(i-1), m)
Inicializao com valor (seed)
help rand

RAND Uniformly distributed random numbers.

RAND produces pseudo-random numbers. The sequence of numbers
generated is determined by the state of the generator. Since MATLAB
resets the state at start-up, the sequence of numbers generated will
be the same unless the state is changed.

S = RAND('state') is a 35-element vector containing the current state
of the uniform generator. RAND('state',S) resets the state to S.
RAND('state',0) resets the generator to its initial state.
RAND('state',J), for integer J, resets the generator to its J-th state.
RAND('state',sum(100*clock)) resets it to a different state each time.

This generator can generate all the floating point numbers in the
closed interval [2^(-53), 1-2^(-53)]. Theoretically, it can generate
over 2^1492 values before repeating itself.
Introduo MatLab AA-0607 26
Exemplo de Funo MATLAB
function [meanr, stdr, z] = simulate(n);

Identificador de funo
Lista de valores de output devolvidos
Nome
funo
Lista de argumentos de entrada,
(separados por vrgula)
Introduo MatLab AA-0607 27
Funo MATLAB
Definio de linha de funo
required of all functions
Lista de inputs e outputs
comma delimited: [y, z] = average(a, b, c)
for more than one output, outputs enclosed in square brackets
Variveis de entrada
function variables are local to the function
input variables are readable to the function: local copies are made if the
inputs need to be changed
Escopo
MATLAB searches in this order:
variable name, subfunction, current directory, MATLAB search path

Introduo MatLab AA-0607 28
Exemplo de Funo MATLAB
function [meanr, stdr, z] = simulate(n);
%
% Funo que simula um vector de n valores uniformemente distribuidos
% calcula e devolve: mdia e desvio padro dos nmeros.
%
%
% INPUTS:
% n: number (inteiro) de ns (pseudo)aleatrios a gerar.
%
% OUTPUTS:
% meanr: mdia dos n ns (pseudo)aleatrios
% stdr: desvio padro dos ns (pseudo)aleatrios
% z: array n x 1 de ns (pseudo)aleatrios


Funes comentadas


Introduo MatLab AA-0607 29
Exemplo de Funo MATLAB
function [meanr, stdr, z] = simulate(n);
%
% Funo que simula um vector de n valores uniformemente distribuidos
% calcula e devolve: mdia e desvio padro dos nmeros.
%
%
% INPUTS:
% n: number (inteiro) de ns (pseudo)aleatrios a gerar.
%
% OUTPUTS:
% meanr: mdia dos n ns (pseudo)aleatrios
% stdr: desvio padro dos ns (pseudo)aleatrios
% z: array n x 1 de ns (pseudo)aleatrios


% simple error checking to check n is a positive integer
if (rem(n,1)~=0) | n<=0
error('Input n must be a positive integer');
end

Validar condies com mensagens erro
Introduo MatLab AA-0607 30
Exemplo de Funo MATLAB


fprintf('Simulating %d random numbers.....\n\n',n);

% generate the n random numbers
z = rand(n,1);

% calculate the mean and standard deviation
meanr= mean(z);
fprintf('Mean of the %d random numbers = %f\n',n,meanr);
stdr= std(z);
fprintf('Standard deviation of the %d random numbers = %f\n',n,stdr);

Simular os nmeros aleatrios.

No necessita de funo return explcita
Valores no devolvidos so locais funo
Introduo MatLab AA-0607 31
Chamada da Funo MATLAB
[m, s] = simulate(1000000);
Simulating 1000000 random numbers.....

Mean of the 1000000 random numbers = 0.499702
Standard deviation of the 1000000 random numbers = 0.499702
[m, s] = simulate(1000000);
Simulating 1000000 random numbers.....

Mean of the 1000000 random numbers = 0.499684
Standard deviation of the 1000000 random numbers = 0.288456

m
m =
0.4997

s
s =
0.2885


Introduo MatLab AA-0607 32
Outra Funo MATLAB
function [meanr, stdr, z] = simplot(n,plotflag);
%
% Funo que simula um vector de n valores uniformemente distribuidos
% calcula e devolve: mdia e desvio padro dos nmeros. Se
% var plotflag for 1 feito o plotting do histogram dos ns gerados.
%
% INPUTS:
% n: number (inteiro) de ns (pseudo)aleatrios a gerar.

% plotflag: se plotflag=1, desenhar histograma de z,
% c.c. no.
%
% OUTPUTS:
% meanr: mdia dos n ns (pseudo)aleatrios
% stdr: desvio padro dos ns (pseudo)aleatrios
% z: array n x 1 de ns (pseudo)aleatrios


% simple error checking to check n is a positive integer
if (rem(n,1)~=0) | n<=0
error('Input n must be a positive integer');
end

Introduo MatLab AA-0607 33
Simplot.m (cont.)
fprintf('Simulating %d random numbers.....\n\n',n);

% generate the n random numbers
z = rand(n,1);

% calculate the mean and standard deviation
meanr= mean(z);
fprintf('Mean of the %d random numbers = %f\n',n,meanr);
stdr= std(z);
fprintf('Standard deviation of the %d random numbers = %f\n',n,stdr);

if nargin>1 & plotflag==1
figure
hist(z, max(n/100,10))
end


Novo cdigo

Nargin n. de argumentos de entrada

sintaxe: hist(data vector, number of bins)
Introduo MatLab AA-0607 34
Fazer o plotting da mdia amostral
em funo de n
Extender simplot.m
Para cada valor i = 1 n, calcular
mean(i) = [sum (x(i) x(i)) ]/I
mean(i) deve convergir para true mean 0.5 para n>>>
Lei dos grandes nmeros da estatstica

Fazer plot para visualizar
Caractersticas de plotting acrescidas
grids, log axes, labels, titles
Introduo MatLab AA-0607 35
Cdigo acrescentado ao simplot.m
if nargin>1 & plotflag==1
figure % figure for a histogram to see how uniform the numbers are
hist(z,max(n/100,10))

figure % figure to see visually how the sample mean converges to 0.5
cs = cumsum(z); % generate a vector of cumulative sums
ns = 1:n; % generate a vector of sample sizes
runningmean = cs./ns; % calculate the running mean
plot(ns,runningmean);
%runningmean = cs./ns';
%semilogx(ns,runningmean);
%grid;
%axis([1 n 0 1]);
%xlabel('Number of random numbers generated');
%ylabel('Mean value');
%title('Convergence of sample mean to true mean');

end


Exerccios
Introduo MatLab AA-0607 37
1 - Para as matrizes A e B, definidas a baixo, execute as seguintes
operaes e interprete os resultados.






a) A+B b) A*B c) A.*B d) A.^2
e) A^2 f) A*A g) inv(A) h) inv(A)*A
i) A\A j) A/A k) A/A eye(3)
l) A*inv(A) eye(3)

(
(
(

=
(
(
(

=
0 7 3
1 1 0
0 1 3
1 1 3
2 1 0
3 2 1
B A
Introduo MatLab AA-0607 38
2 Utilizando as funes zeros, ones e eye construa as seguintes
matrizes:
(

=
(

=
(
(
(

=
(
(
(
(

=
1 0
0 1
1
1
1 1 1
1 1 1
1 1 1
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
D C B A
zeros(4) ones(3) ones(2,1) eye(2)
Introduo MatLab AA-0607 39
3 A partir das matrizes A e B do exerccio 2 e D = [A B]
verifique quais so as operaes vlidas.

a) A*D b) D*A c) D*A d) A*D*B

e) A*B*D f) A*D g) D(:,1:3)*A

h) D(1:3,:)*A


Introduo MatLab AA-0607 40
4 A partir de um conjunto 500 de valores aleatrios com
distribuio normal (mdia 10 e desvio padro 2)
determine a percentagem de valores:
a) superiores a 10
b) entre 8 e 12;
c) entre 6 e 14;
d) entre 6 e 14;
e) superiores a 15.


5- Represente graficamente a funo de densidade de
probabilidade da distribuio normal reduzida, no
intervalo de -3 a 3.
2
2
2
1
) (
x
e x f

=
t
Introduo MatLab AA-0607 41
6 A partir de um conjunto de 100 valores aleatrios com mdia 500 e desvio
padro 100, representando uma srie de valores anuais de precipitao entre
1900 e 1999, elabore um programa que:
a) Represente graficamente esta srie temporal (Figura 1).
b) Conte o nmero de ocorrncias em que a precipitao excedeu o valor mdio mais duas
vezes o desvio padro (valores considerados anmalos).
c) Represente no grfico, atravs de crculos pretos, os valores anteriores.
d) Utilizando a funo hist, construa um histograma, com 20 classes, que represente a
distribuio da precipitao (Figura 2).

1900 1920 1940 1960 1980 2000
250
300
350
400
450
500
550
600
650
700
750
Ano
P
r
e
c
i
p
i
t
a

o

Figura 1
250 300 350 400 450 500 550 600 650 700
0
2
4
6
8
10
12
14
Figura 2

Anda mungkin juga menyukai