intro duca om at lab

Upload: lkarolino

Post on 04-Apr-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Intro Duca Om at Lab

    1/41

    Breve Introduo Programao em MATLAB

    Aulas Prticas de Aprendizagem Automtica

    Ano Lectivo 2006/2007

    Susana Nascimento

    Departamento de Informtica

    [email protected]

  • 7/29/2019 Intro Duca Om at Lab

    2/41

    Introduo MatLab AA-0607 2

    Introduo ao MatLabO ambiente de trabalho das aulas prticas: MATLAB.

    O MATLAB um ambiente de programao de alto nvel paraaplicaes 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.

    http://www.mathworks.com/http://www.mathworks.com/
  • 7/29/2019 Intro Duca Om at Lab

    3/41

    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

    http://www.mathworks.com/products/http://www.mathworks.com/products/http://www.mathworks.com/products/http://www.mathworks.com/products/http://www.mathworks.com/access/helpdesk/help/techdoc/learn_matlab/learn_matlab.shtmlhttp://www.mathworks.com/access/helpdesk/help/techdoc/learn_matlab/learn_matlab.shtmlhttp://www.mathworks.com/http://www.mathworks.com/products/http://www.mathworks.com/products/http://www.mathworks.com/products/http://www.mathworks.com/products/http://www.mathworks.com/products/http://www.mathworks.com/products/http://www.mathworks.com/products/http://www.mathworks.com/products/http://www.mathworks.com/products/
  • 7/29/2019 Intro Duca Om at Lab

    4/41

    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

  • 7/29/2019 Intro Duca Om at Lab

    5/41

    Introduo MatLab AA-0607 5

  • 7/29/2019 Intro Duca Om at Lab

    6/41

    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)

  • 7/29/2019 Intro Duca Om at Lab

    7/41

    Introduo MatLab AA-0607 7

    Uint8 e Doubles

    Double

    Maioria funes MATLAB

    doubles como argumento de entrada

    return double

  • 7/29/2019 Intro Duca Om at Lab

    8/41

    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 operaomatemtica

    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

  • 7/29/2019 Intro Duca Om at Lab

    9/41

    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

  • 7/29/2019 Intro Duca Om at Lab

    10/41

    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

  • 7/29/2019 Intro Duca Om at Lab

    11/41

    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

  • 7/29/2019 Intro Duca Om at Lab

    12/41

    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

  • 7/29/2019 Intro Duca Om at Lab

    13/41

    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: 4data: []

    image(1)

    ans =

    name: 'Tom'height: 3

    width: 3

    data: [3x3 double]

  • 7/29/2019 Intro Duca Om at Lab

    14/41

    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)

  • 7/29/2019 Intro Duca Om at Lab

    15/41

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

  • 7/29/2019 Intro Duca Om at Lab

    16/41

    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 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/2

    ans =

    2.0000 2.5000

  • 7/29/2019 Intro Duca Om at Lab

    17/41

    Introduo MatLab AA-0607 17

    Operadores Relacionais

    =, ==, ~=

    compare corresponding elements

    of 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

  • 7/29/2019 Intro Duca Om at Lab

    18/41

    Introduo MatLab AA-0607 18

    Operadores Relacionais

    =, ==, ~=

    compare corresponding elements

    of 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

    a

    a =

    2 3

    b

    b =

    4 5

    a > b

    ans =

    0 0

    b > a

    ans =1 1

    a > 2

    ans =

    0 1

  • 7/29/2019 Intro Duca Om at Lab

    19/41

    Introduo MatLab AA-0607 19

    Fluxo de Controlo

    If, else, endif

    if index

  • 7/29/2019 Intro Duca Om at Lab

    20/41

    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

  • 7/29/2019 Intro Duca Om at Lab

    21/41

    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

  • 7/29/2019 Intro Duca Om at Lab

    22/41

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

    Inicializao de variveis

    Print de informao para o ecran

  • 7/29/2019 Intro Duca Om at Lab

    23/41

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

    e correspondente soma usando loop for;

    (2) Calcular tempo execuo;

    (3) mostrar resultado

  • 7/29/2019 Intro Duca Om at Lab

    24/41

    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

  • 7/29/2019 Intro Duca Om at Lab

    25/41

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

  • 7/29/2019 Intro Duca Om at Lab

    26/41

    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)

  • 7/29/2019 Intro Duca Om at Lab

    27/41

    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 theinputs need to be changed

    Escopo MATLAB searches in this order:

    variable name, subfunction, current directory, MATLAB search path

  • 7/29/2019 Intro Duca Om at Lab

    28/41

    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

  • 7/29/2019 Intro Duca Om at Lab

    29/41

    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 integerif (rem(n,1)~=0) | n

  • 7/29/2019 Intro Duca Om at Lab

    30/41

    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 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 nmeros aleatrios.

    No necessita de funo return explcita

    Valores no devolvidos so locais funo

  • 7/29/2019 Intro Duca Om at Lab

    31/41

    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

  • 7/29/2019 Intro Duca Om at Lab

    32/41

    Introduo MatLab AA-0607 32

    Outra Funo MATLABfunction [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

  • 7/29/2019 Intro Duca Om at Lab

    33/41

    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)

  • 7/29/2019 Intro Duca Om at Lab

    34/41

    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 mean0.5 para n>>>

    Lei dos grandes nmeros da estatstica

    Fazer plot para visualizar

    Caractersticas de plotting acrescidas

    grids, log axes, labels, titles

  • 7/29/2019 Intro Duca Om at Lab

    35/41

    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 meanplot(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

  • 7/29/2019 Intro Duca Om at Lab

    36/41

    Exerccios

  • 7/29/2019 Intro Duca Om at Lab

    37/41

    Introduo MatLab AA-0607 37

    1 - Para as matrizes A e B, definidas a baixo, execute as seguintesoperaes 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)*A

    i) A\A j) A/A k) A/Aeye(3)

    l) A*inv(A)eye(3)

    073

    110013

    113

    210321

    BA

  • 7/29/2019 Intro Duca Om at Lab

    38/41

    Introduo MatLab AA-0607 38

    2Utilizando as funes zeros, onese eyeconstrua as seguintesmatrizes:

    10

    01

    1

    1

    111

    111111

    0000

    0000

    0000

    0000

    DCBA

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

  • 7/29/2019 Intro Duca Om at Lab

    39/41

    Introduo MatLab AA-0607 39

    3A 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

  • 7/29/2019 Intro Duca Om at Lab

    40/41

    Introduo MatLab AA-0607 40

    4A partir de um conjunto 500 de valores aleatrios comdistribuio normal (mdia 10 e desvio padro 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 funo de densidade de

    probabilidade da distribuio normal reduzida, nointervalo de -3 a 3.

    2

    2

    2

    1)(

    x

    exf

  • 7/29/2019 Intro Duca Om at Lab

    41/41

    I d M L b AA 0607 41

    6 A partir de um conjunto de 100 valores aleatrios com mdia 500 e desviopadro 100, representando uma srie de valores anuais de precipitao entre1900 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 duasvezes 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 2000250

    300

    350

    400

    450

    500

    550

    600

    650

    700

    750

    i

    i

    Figura 1

    250 300 350 400 450 500 550 600 650 7000

    2

    4

    6

    8

    10

    12

    14

    Figura 2