Introd MatLab

Download Report

Transcript Introd MatLab

Breve Introdução à
Programação em MATLAB
Aulas Práticas de Aprendizagem Automática
Ano Lectivo 2006/2007
Susana Nascimento
Departamento de Informática
[email protected]
Introdução ao MatLab
O ambiente de trabalho das aulas práticas: MATLAB.
O MATLAB é um ambiente de programação de alto nível para
aplicações Científicas e de Engenharia.
Facilidades
 Oferece um leque alargado de bibliotecas de funções prédefinidas.
 Muito amigável em funcionalidades gráficas para Visualização de
Dados.
 Largamente divulgado em Universidades e Laboratórios de
Investigação.
 Muito conveniente para o desenvolvimento eficás de protótipos.
Introdução MatLab AA-0607
2
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
Introdução MatLab AA-0607
3
Sumário
• Tipos de dados
– arrays: caracteres, numéricos, estruturados, …
• Operadores
– aritmética, relacionais, lógicos.
• Fluxo de Controlo
– condicionais, case, while, etc.
• M-functions
– sintaxe
– Exemplos e funções simples
Introdução MatLab AA-0607
4
Introdução MatLab AA-0607
5
Tipos de Dados em MatLab
Array
Char
‘a’
Numeric
Uint8
(8 bit unsigned integer,
from 0 to 255,
e.g., image gray scales)
Structure
image.width = 120
image.name = ‘face1’
Cell
Double
e.g., 3.2567
(8 bytes)
Introdução MatLab AA-0607
6
Uint8 e Doubles
• Double
– Maioria funções MATLAB
• doubles como argumento de entrada
• return double
Introdução MatLab AA-0607
7
Uint8 e Doubles
• Double
– Maioria funções MATLAB
• doubles como argumento de entrada
• return double
• e.g.,
» 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
b
• Necessidade de converter ‘uint8’ para
‘double’ antes de realizar operação
matemática
1x10
1x10
80 double array
10 uint8 array
» b*2
??? Error using ==> *
Function '*' not defined for variables of class 'uint8'.
» (double(b))*2
ans =
2
Introdução MatLab AA-0607
4
6
8 10 12 14 16 18 20
8
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
Introdução MatLab AA-0607
9
Tipo de Dados ‘Char’
» c = ['hello'];
» whos
Name
Size
Bytes Class
c
1x5
10 char array
Grand total is 5 elements using 10 bytes
» d = [c,' again'];
»d
d=
hello again
»
» b = ['hello';'again'];
» size(b)
ans =
2 5
»b
b=
hello
again
»
» c(1)
ans =
h
Introdução MatLab AA-0607
10
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
image
Size
1x1
Bytes Class
590 struct array
Grand total is 18 elements using 590 bytes
Introdução MatLab AA-0607
11
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
Introdução MatLab AA-0607
12
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
» image(2)
ans =
name: 'Mary'
height: 4
width: 4
data: []
894 struct array
Grand total is 28 elements using 894 bytes
» image(1)
» image
ans =
image =
name: 'Tom'
height: 3
width: 3
data: [3x3 double]
1x2 struct array with fields:
name
height
width
data
Introdução MatLab AA-0607
13
Operadores
• Aritméticos
– Computação numérica, e.g., 2^10
• Relacional
– Comparação quantitativa de operandos
– e.g., a < b
• Lógico
– AND, OR, NOT
– Devolve variável Booleana, 1 (TRUE) ou 0 (FALSE)
Introdução MatLab AA-0607
14
Operadores Aritméticos
• 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
Introdução MatLab AA-0607
15
Operadores Aritméticos
• Transpose, a’
• Power, a^2
• Addition, multiplication, division
– a(1)*b(2)
– a*b
» a = [2 3];
» b = [4 5];
» a(1)*b(2)
ans =
10
» a*b
??? Error using ==> *
Inner matrix dimensions must agree.
• 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
Introdução MatLab AA-0607
» a*b'
ans =
23
» a.*b
ans =
8 15
» b/2
ans =
2.0000 2.5000
16
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
Introdução 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
»a
a=
2
3
»b
b=
4
5
»a>b
ans =
0 0
»b>a
ans =
1 1
»a>2
ans =
0 1
Introdução MatLab AA-0607
18
Fluxo de Controlo
• If, else, endif
– if index<100
statements
else
statements
end
• For…..
– For i = 1:100
statements
end
• Switch, while
Introdução MatLab AA-0607
19
Programação 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
Introdução MatLab AA-0607
20
Exemplo de Script MATLAB
% script randVect
% Script simples para gerar um vector de n n. aleatórios.
% ilustar aplicando:
%
(a) loops for, and (b) chamada directa a uma função.
%
%
Comentar o código
Introdução MatLab AA-0607
21
Exemplo de Script MATLAB
% script randVect
% Script simples para gerar um vector de n n. aleatórios.
% ilustar aplicando:
%
(a) loops for, and (b) chamada directa a uma função.
%
%
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);
Inicialização de variáveis
Print de informação para o ecran
Introdução MatLab AA-0607
22
Exemplo de Script MATLAB
% script randVect
% Script simples para gerar um vector de n n. aleatórios.
% ilustar aplicando:
%
(a) loops for, and (b) chamada directa a uma função.
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');
(1) Calcula n n. aleatórios
tic % set the timer
e correspondente soma usando loop for;
for i=1:n
(2) Calcular tempo execução;
y(i) = rand(1);
end
(3) mostrar resultado
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);
…...
Introdução MatLab AA-0607
23
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. aleatórios
e correspondente soma usando função rand;
(2) Calcular tempo execução;
(3) mostrar resultado
Introdução MatLab AA-0607
24
Gerador de Números (pseudo)aleatórios
em MatLab
• Gera sequência (of length n) de nºs pseudoaleatórios:
– Geração da sequência: x(i) = mod(a * x(i-1), m)
– Inicialização 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.
Introdução MatLab AA-0607
25
Exemplo de Função MATLAB
function [meanr, stdr, z] = simulate(n);
Lista de argumentos de entrada,
(separados por vírgula)
Nome
função
Identificador de função
Lista de valores de output devolvidos
Introdução MatLab AA-0607
26
Função MATLAB
• Definição de linha de função
– 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
• Variáveis 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
Introdução MatLab AA-0607
27
Exemplo de Função MATLAB
function [meanr, stdr, z] = simulate(n);
%
% Função que simula um vector de n valores uniformemente distribuidos
% calcula e devolve: média e desvio padrão dos números.
%
%
% INPUTS:
%
n: number (inteiro) de nºs (pseudo)aleatórios a gerar.
%
% OUTPUTS:
%
meanr: média dos n nºs (pseudo)aleatórios
%
stdr: desvio padrão dos nºs (pseudo)aleatórios
%
z:
array n x 1 de nºs (pseudo)aleatórios
Funções comentadas
Introdução MatLab AA-0607
28
Exemplo de Função MATLAB
function [meanr, stdr, z] = simulate(n);
%
% Função que simula um vector de n valores uniformemente distribuidos
% calcula e devolve: média e desvio padrão dos números.
%
%
% INPUTS:
%
n: number (inteiro) de nºs (pseudo)aleatórios a gerar.
%
% OUTPUTS:
%
meanr: média dos n nºs (pseudo)aleatórios
%
stdr: desvio padrão dos nºs (pseudo)aleatórios
%
z:
array n x 1 de nºs (pseudo)aleatórios
% 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 condições com mensagens erro
Introdução MatLab AA-0607
29
Exemplo de Função 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 números aleatórios.
Não necessita de função return explícita
Valores não devolvidos são locais à função
Introdução MatLab AA-0607
30
Chamada da Função 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
»
Introdução MatLab AA-0607
31
Outra Função MATLAB
function [meanr, stdr, z] = simplot(n,plotflag);
%
% Função que simula um vector de n valores uniformemente distribuidos
% calcula e devolve: média e desvio padrão dos números. Se
% var plotflag for 1 é feito o plotting do histogram dos nºs gerados.
%
% INPUTS:
%
n: number (inteiro) de nºs (pseudo)aleatórios a gerar.
%
plotflag: se plotflag=1, desenhar histograma de z,
%
c.c. não.
%
% OUTPUTS:
%
meanr: média dos n nºs (pseudo)aleatórios
%
stdr: desvio padrão dos nºs (pseudo)aleatórios
%
z:
array n x 1 de nºs (pseudo)aleatórios
% 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
Introdução MatLab AA-0607
32
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 código
Nargin n. de argumentos de entrada
sintaxe: hist(data vector, number of bins)
Introdução MatLab AA-0607
33
Fazer o plotting da média amostral
em função 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 números” da estatística
– Fazer plot para visualizar
– Características de plotting acrescidas
• grids, log axes, labels, titles
Introdução MatLab AA-0607
34
Código 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
Introdução MatLab AA-0607
35
Exercícios
1 - Para as matrizes A e B, definidas a baixo, execute as seguintes
operações e interprete os resultados.
1 2 3
A  0 1 2 


3 1 1
a) A+B
b) A*B
e) A^2
f) A*A
i) A\A
j) A/A
l) A*inv(A) – eye(3)
3 1 0
B  0 1 1 


3 7 0
c) A.*B
d) A.^2
g) inv(A)
h) inv(A)*A
k) A/A – eye(3)
Introdução MatLab AA-0607
37
2 – Utilizando as funções zeros, ones e eye construa as seguintes
matrizes:
0
0
A
0
0

0 0 0
0 0 0

0 0 0
0 0 0
zeros(4)
1 1 1
B  1 1 1


1 1 1
ones(3)
Introdução MatLab AA-0607
1
C 
1
ones(2,1)
1 0
D

0
1


eye(2)
38
3 – A partir das matrizes A e B do exercício 2 e D = [A B]
verifique quais são as operações válidas.
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
Introdução MatLab AA-0607
39
4 – A partir de um conjunto 500 de valores aleatórios com
distribuição normal (média 10 e desvio padrão 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 função de densidade de
probabilidade da distribuição normal reduzida, no
intervalo de -3 a 3.
f ( x) 
x2
1 2
e
2
Introdução MatLab AA-0607
40
6 – A partir de um conjunto de 100 valores aleatórios com média 500 e desvio
padrão 100, representando uma série de valores anuais de precipitação entre
1900 e 1999, elabore um programa que:
a) Represente graficamente esta série temporal (Figura 1).
b) Conte o número de ocorrências em que a precipitação excedeu o valor médio mais duas
vezes o desvio padrão (valores considerados anómalos).
c) Represente no gráfico, através de círculos pretos, os valores anteriores.
d) Utilizando a função hist, construa um histograma, com 20 classes, que represente a
distribuição da precipitação (Figura 2).
14
750
700
12
650
10
Precipitação
600
550
8
500
6
450
400
4
350
2
300
250
1900
1920
1940
1960
1980
2000
0
250
300
350
400
450
500
550
600
650
700
Ano
Figura 1
Figura 2
Introdução MatLab AA-0607
41