Upload
internet
View
108
Download
1
Embed Size (px)
Citation preview
Introdução ao MATLABpara Hidrólogos
Computação Interativa
Porto Alegre, outubro de 2005
Programação• On-line help e Funções do MATLAB• Como Carregar Dados
– Importar Arquivos de Dados
• Matrizes e Vetores– Entrada, Indexação, Manipulação, Criação de
Vetores
• Operações de Matrizes– Aritméticas, Relacionais, Lógicas, Funções,
Caracteres
• Funções Inline• Como Plotar Gráficos Simples• Como Salvar Dados
On-line Help e Funções do MATLAB
• help>> help cumsum CUMSUM Cumulative sum of elements. For vectors, CUMSUM(X) is a vector containing the cumulative sum of
the elements of X. For matrices, CUMSUM(X) is a matrix the same size as X containing the cumulative sums over each column. For N-D arrays, CUMSUM(X) operates along the first non-singleton dimension.
CUMSUM(X,DIM) works along the dimension DIM. Example: If X = [0 1 2 3 4 5] then cumsum(X,1) is [0 1 2 3 5 7] and
cumsum(X,2) is [0 1 3 3 7 12] See also cumprod, sum, prod.
Overloaded functions or methods (ones with the same name in other directories)
help fints/cumsum.m
Reference page in Help browser doc cumsum
On-line Help e Funções do MATLAB
• helpwin• helpdesk• lookfor
>> helpwin>> helpdesk>> lookfor 'boxcox'BOXCOX transforms non-normally distributed data to normally distributed
data. MV_BOXCOX box-cox transformation guiboxcox.m: %@FINTS/BOXCOX transforms non-normally distributed FINTS
object to a normal one.
Como Carregar Dados
• Importando dados (ver “fileformats”, “iofun”)
>> load data>> AA = 9 6 3 8 5 2 7 4 1
>> A = importdata('dados.xls')A = Plan1: [3x3 double]
>> A.Plan1ans = 2 8 1 4 7 6 5 9 3
>> B = xlsread('dados.xls')B = 2 8 1 4 7 6 5 9 3
Como Carregar Dados
• Exercício–Carregar dados de vazão do
arquivo ‘Tres_Marias.xls’ usando TM = ‘importdata’ e Q = ‘xlsread’
Como Carregar Dados
• Exercício
>> TM = xlsread('Tres_Marias.xls');
>> Q = importdata('Tres_Marias.xls')
Q =
data: [1x1 struct] textdata: [1x1 struct] rowheaders: [1x1 struct]
Matrizes e Vetores
• Entrada–Usando
funções prontas;
>> A = logspace(0,5,6)
A =
1 10 100 1000 10000 100000
>> A = randn(3)
A =
-0.0956 -1.3362 -0.6918 -0.8323 0.7143 0.8580 0.2944 1.6236 1.2540
Matrizes e Vetores
• Entrada–Digitando
diretamente;• “...” continua
na linha seguinte
• “[]” matriz nula
>> A = [1 2 3; 4 5 6; 7 8 9]A = 1 2 3 4 5 6 7 8 9
>> A = [9 8 76 5 43 2 1]A = 9 8 7 6 5 4 3 2 1
>> A = [1 2 3; 4 5 ...6; 7 8 9]A = 1 2 3 4 5 6 7 8 9
>> A = []A = []
Matrizes e Vetores
• Exercício–Criar matriz chuva
com os dados:
–Criar matriz (q) de vazão com 366 valores, através de função pronta (randn).• Dica: Usar B =
exp(6.3+0.8*randn)
98,0
05,1
13,1
22,1
33,1
47,1
65,1
90,1
26,2
85,2
P
Matrizes e Vetores
• Indexação–Referenciando por:
• Matriz(linha,coluna)• Matriz(nº do
elemento)
>> A = [1 2 3; 4 5 6; 7 8 9]A = 1 2 3 4 5 6 7 8 9
>> A(6)ans = 8
>> A(2,2)ans = 5
>> A(2,2) = 1A = 1 2 3 4 1 6 7 8 9
Matrizes e Vetores
• Indexação–Referenciando por:
• Matriz(sub-matriz)–Determinação
automática de dimensões;
>> B = A(2:3,:)B = 4 1 6 7 8 9
>> B(:,3)=[]B = 4 1 7 8
>> C (2,3) = 4C = 0 0 0 0 0 4
>> D (2, 1:2) = 8D = 0 0 8 8
Matrizes e Vetores
• Exercício– Descobrir a vazão e a que dia
pertencem a posição 60
– Qual o último dia da série?
– E o primeiro?
– Rearrumar matriz P pelo método dos blocos alternados
Matrizes e Vetores
• Exercício– Descobrir a vazão e a
que dia pertencem a posição 60
– Qual o último dia da série?
– E o primeiro?
>> TM(60)ans = 730.8000
>> Q.dataans = Sheet1: [7670x1 double]
>> Q.data.Sheet1(60)ans = 730.8000
>> Q.textdata.Sheet1(60)ans = '1/3/1977‘
>> Q.textdata.Sheet1(end)ans = '31/12/1997'
>> Q.textdata.Sheet1(1)ans = '1/1/1977'
Matrizes e Vetores
• Manipulação de Matrizes–Indexação–Reforma
(vetor matriz)
>> A = [1 2 3; 4 5 6; 7 8 9];
>> v = [1 3];
>> B = A(v,:)B = 1 2 3 7 8 9
>> x = B(:)x = 1 7 2 8 3 9
>> C = reshape(x,3,2)C = 1 8 7 3 2 9
Matrizes e Vetores
• Manipulação de Matrizes–Transposição–Inicialização–Anexação e
Retirada (vetor ou escalar)
>> C = C'C = 1 7 2 8 3 9
>> x = transp(C(:,2))x = 7 3
>> C = sparse(1000000,2)C = All zero sparse: 1000000-by-2
>> v = [8 7 3];
>> B = [A; v]B = 1 2 3 4 5 6 7 8 9 8 7 3
>> B(end,:) = []B = 1 2 3 4 5 6 7 8 9
Matrizes e Vetores
• Manipulação de Matrizes–Matrizes “úteis”:
ones, zeros, rand, size, length, numel, find, nonzeros, max, min
>> A = ones(2,2)A = 1 1 1 1
>> A = zeros(2,2)A = 0 0 0 0
>> size(B)ans = 3 3
>> length(B)ans = 3
>> numel(B)ans = 9
Matrizes e Vetores
• Manipulação de Matrizes–Matrizes “úteis”:
ones, zeros, rand, size, length, numel, find, nonzeros, max, min
>> A(1,:) = 8;
>> [a,b,c]=find(A)a = 1 1b = 1 2c = 8 8
>> s = nonzeros (A)s = 8 8
Matrizes e Vetores
• Exercício–Agregar matriz q ao fim da matriz
TM (TMq)–Determinar posição e valores
máximos e mínimos de TM e de TMq
–Encontre datas correspondentes–Refaça os procedimentos apenas
para o período a década de 80
Matrizes e Vetores
• Criação de Vetoresv = valor inicial : incremento : valor final
>> s = 0:numel(B)/4:numel(B)s = Columns 1 through 3 0 2.25 4.5 Columns 4 through 5 6.75 9
>> a = [11:13; 3:1]a = 11 12 13
>> a = [11:13; 3:-1:1]a = 11 12 13 3 2 1
Matrizes e Vetores
• Exercício–Refazer método dos blocos
alternados usando criação de matrizes• Dica: Usar um vetor de posições
Matrizes e Vetores
• Exercício
>> pos = [((length(P)-1):-2:1) (2:2:length(P))]pos = 9 7 5 3 1 2 4 6 8 10
>> p=P(pos)p = 1.0500 1.2200 1.4700 1.9000 2.8500 2.2600 1.6500 1.3300 1.1300 0.9800
Operações de Matrizes
• Aritméticas (+,-,*,/,\,^,.)
>> A = [8 1 6; 3 5 7; 4 9 2];
>> B = [2 5 3; 7 9 1; 8 4 6];
>> A*Bans = 71 73 61 97 88 56 87 109 33
>> A\Bans = -0.2056 -0.3083 0.6806 0.8778 0.3167 0.4722 0.4611 1.1917 -0.4861
>> A.^Bans = 64 1 216 2187 1953125 7 65536 6561 64
Operações de Matrizes
• Relacionais (<,>,<=,>=,==,~=)
• Lógicas (&, |, ~, xor)• Funções matemáticas
(sin,csch, exp, log, log10, abs)
• Funções matriciais(sqrtm,expm)
>> A<=Bans = 0 1 0 1 1 0 1 0 1
>> ~(A>B)ans = 0 1 0 1 1 0 1 0 1
>> exp(A)ans = 1.0e+003 * 2.9810 0.0027 0.4034 0.0201 0.1484 1.0966 0.0546 8.1031 0.0074
>> expm(A)ans = 1.0e+006 * 1.0898 1.0896 1.0897 1.0896 1.0897 1.0897 1.0896 1.0897 1.0897
Operações de Matrizes
• Variáveis de caracteres
• Funções “úteis” (any, all, rem, ceil, floor, disp, error, findstr, strcat, strcmp, datestr)
>> nome = 'Curso'nome =Curso
>> nome(3)ans =r
>> datestr(60,6)ans =02/29
>> (A>B)|(rem(A,2)~=0)ans = 1 1 1 1 1 1 0 1 0
Operações de Matrizes
• Funções “úteis” (any, all, rem, ceil, floor, disp, error, findstr, strcat, strcmp, datestr)
>> a = 'Número de parâmetros de entrada insuficiente';>> disp(a)Número de parâmetros de entrada insuficiente>> error(a)??? Número de parâmetros de entrada insuficiente
Operações de Matrizes
• Exercício–Determinar TM90, TM95
• Dica:–Reordenar vetor de dados–Criar outro com mesmo tamanho–Calcular permanência–Interpolar usando relações
aritméticas
Funções In-line• Aplica-se a funções
simples apenas (usar m-files para funções mais complexas)
ExercícioDados:Q = 15 m3/sS = 0,001 m/mn = 0,02b = 8 my = ?Dicas: usar Q = AR2/3S1/2 e yk+1 = g(yk)
n
>> f = inline('a^2+b^3')
f =
Inline function: f(a,b) = a^2+b^3
>> f(3,2)
ans =
17
Como Plotar Gráficos Simples
• 2D(plot, fplot, ezplot, ezpolar, ezcontour, ezcontourf, hist, bar, normplot)
• 3D(ezplot3, ezsurf, ezsurfc)
>> SF = importdata ('Paulo_Afonso-Moxoto_SF.xls')SF = data: [7670x2 double] textdata: {7671x3 cell}>> obs=SF.data(:,1);>> calc=SF.data(:,2);>> subplot(2,2,1),plot(1:length(obs),obs,1:length(calc),calc)>> subplot(2,2,2),scatter(obs,calc)>> subplot(2,2,3),bar([obs(1:365:3650) calc(1:365:3650)])>> subplot(2,2,4),semilogy(1:length(obs),obs)
Como Plotar Gráficos Simples
• 2D(plot, fplot, ezplot, ezpolar, ezcontour, ezcontourf, hist, bar, normplot)
• 3D(ezplot3, ezsurf, ezsurfc)>> Z = importdata('MNT.txt');>> surf (Z, 'FaceColor','interp',...'EdgeColor','none',...'FaceLighting','phong')
Como Salvar Dados
• Arquivos .mat (binário)–matlab.mat (default)
>> A = reshape(9:-1:1,3,3);>> save data A>> save a.dat A –ascii>> clear A>> A??? Undefined function or
variable 'A'.
Exercícios
• Salvar arquivo de dados de Vazão diária
• Salvar arquivo de precipitação
Computação Interativa
• Exercício–Reorganizar Q para vetores
por dia juliano–Plotar a média diária
• Dica:–Usar struct–Ver datestr, strcat (29/02),
datenum–Indexação usando contador–Usar “for”
Computação Interativa
• Exercício
tot = 366; n = length(Q.data.Sheet1);
ini = datenum(Q.textdata.Sheet1(1)); cont = 0;
for i = 1:tot,
Qdi(i).dados = sparse(round(n/365.25),1);
end
Qdi(60).dados = sparse (floor(round(n/365.25)/4),1);
comp1 = datenum(strcat(datestr(1:tot,6),'/00'))';
comp2 = datenum(strcat(datestr((1:n)'+ini-1,6),'/00'));
for i = 1:tot,
for j = 1:n,
if comp1(i) == comp2(j),
cont = cont +1;
Qdi(i).dados(cont) = Q.data.Sheet1(j);
end
end
cont = 0;
end