breve introdução à programação em matlab aulas práticas de aprendizagem automática ano...

41
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]

Upload: internet

Post on 17-Apr-2015

104 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Breve Introdução à Programação em

MATLAB

Aulas Práticas de Aprendizagem Automática

Ano Lectivo 2006/2007Susana Nascimento

Departamento de Informá[email protected]

Page 2: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 2

Introdução ao MatLabO 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.

Page 4: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 4

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

Page 5: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 5

Page 6: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução 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)

Doublee.g., 3.2567(8 bytes)

Page 7: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 7

Uint8 e Doubles

• Double– Maioria funções MATLAB

• doubles como argumento de entrada• return double

Page 8: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 8

Uint8 e Doubles

• Double– Maioria funções MATLAB

• doubles como argumento de entrada

• return double• e.g.,

• Necessidade de converter ‘uint8’ para‘double’ antes de realizar operação matemática

» a = 1:10a =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

Page 9: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 9

Tipo ‘Char’

» c = ['hello'];» whos Name Size Bytes Class c 1x5 10 char arrayGrand total is 5 elements using 10 bytes

» c(1)ans =h

Page 10: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 10

Tipo de Dados ‘Char’

» c = ['hello'];» whos Name Size Bytes Class c 1x5 10 char arrayGrand total is 5 elements using 10 bytes

» c(1)ans =h

» d = [c,' again'];» dd =hello again» » b = ['hello';'again'];» size(b)ans = 2 5» bb =helloagain»

Page 11: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução 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

Page 12: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução 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

Page 13: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução 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]

Page 14: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 14

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)

Page 15: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 15

Operadores Aritméticos

• Transpose, a’• Power, a^2• Addition, multiplication, division

– a(1)*b(2)– a*b

• works if a and b are matriceswith appropriate dimensions(columns(a) = rows(b))

– a.*b (element by element)

• except for matrix operations, mostoperands must be of the same size,unless one is a scalar

Page 16: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 16

Operadores Aritméticos

• Transpose, a’• Power, a^2• Addition, multiplication, division

– a(1)*b(2)– a*b

• works if a and b are matriceswith 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.*bans =

8 15

» b/2ans = 2.0000 2.5000

Page 17: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 17

Operadores Relacionais

• <, <=, >, >=, ==, ~=

• compare corresponding elementsof arrays with same dimensions

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

• result is, element by element, 1 or 0

Page 18: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 18

Operadores Relacionais

• <, <=, >, >=, ==, ~=

• compare corresponding elementsof arrays with same dimensions

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

• result is element by element 1 or 0

» aa = 2 3

» bb = 4 5

» a > bans = 0 0

» b > aans = 1 1

» a > 2ans = 0 1

Page 19: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 19

Fluxo de Controlo

• If, else, endif– if index<100

statementselse statementsend

• For…..– For i = 1:100

statementsend

• Switch, while

Page 20: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 20

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

Page 21: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

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.%%

Comentar o código

Page 22: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

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 yfprintf('Simulating %d random numbers.....\n\n',n);

Inicialização de variáveis

Print de informação para o ecran

Page 23: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 23

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 yfprintf('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);endtotal = 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. aleatóriose correspondente soma usando loop for; (2) Calcular tempo execução; (3) mostrar resultado

Page 24: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 24

Exemplo de Script MATLAB

…………% now do the calculation using vectorizationfprintf('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óriose correspondente soma usando função rand; (2) Calcular tempo execução; (3) mostrar resultado

Page 25: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 25

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.

Page 26: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 26

Exemplo de Função MATLAB

function [meanr, stdr, z] = simulate(n);

Identificador de função

Lista de valores de output devolvidos

Nomefunção

Lista de argumentos de entrada,(separados por vírgula)

Page 27: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 27

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

Page 28: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

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

Funções comentadas

Page 29: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 29

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 integerif (rem(n,1)~=0) | n<=0 error('Input n must be a positive integer');end

Validar condições com mensagens erro

Page 30: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 30

Exemplo de Função MATLAB

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

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

% calculate the mean and standard deviationmeanr= 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ícitaValores não devolvidos são locais à função

Page 31: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 31

Chamada da Função MATLAB

» [m, s] = simulate(1000000);Simulating 1000000 random numbers.....

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

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

» mm = 0.4997

» ss =0.2885

»

Page 32: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 32

Outra Função MATLABfunction [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 integerif (rem(n,1)~=0) | n<=0 error('Input n must be a positive integer');end

Page 33: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 33

Simplot.m (cont.)

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

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

% calculate the mean and standard deviationmeanr= 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)

Page 34: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 34

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

Page 35: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 35

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

Page 36: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Exercícios

Page 37: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 37

1 - Para as matrizes A e B, definidas a baixo, execute as seguintes operações e interprete os resultados.

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

073

110

013

113

210

321

BA

Page 38: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 38

2 – Utilizando as funções zeros, ones e eye construa as seguintes matrizes:

10

01

1

1

111

111

111

0000

0000

0000

0000

DCBA

zeros(4) ones(3) ones(2,1) eye(2)

Page 39: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 39

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

 

Page 40: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 40

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 10b)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.

2

2

21

)(

x

exf

Page 41: Breve Introdução à Programação em MATLAB Aulas Práticas de Aprendizagem Automática Ano Lectivo 2006/2007 Susana Nascimento Departamento de Informática

Introdução MatLab AA-0607 41

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).    

1900 1920 1940 1960 1980 2000250

300

350

400

450

500

550

600

650

700

750

Ano

Pre

cip

itaçã

o

Figura 1

250 300 350 400 450 500 550 600 650 7000

2

4

6

8

10

12

14

Figura 2