Análise de Sinais
(5001)
Ficha Prática Laboratorial VI
Curso: Ciências Biomédicas
Duração prevista: 2 horas
Séries de Fourier usando a toolbox
Symbolic do MatLab
I. Introdução à toolbox Symbolic
A Toolbox symbolic do MatLab é capaz de realizar processamento simbólico. Antes que as suas funções
possam ser usadas temos que informar o MatLab de que as variáveis a usar são simbólicas. Esta tarefa é
desempenhada pelo comando syms. Para o perceber melhor devemos fazer help syms no prompt e ler
com cuidado a informação devolvida.
>> help syms
SYMS Short-cut for constructing symbolic objects. SYMS arg1 arg2 ...
is short-hand notation for arg1 = sym('arg1'); arg2 = sym('arg2'); ...
SYMS arg1 arg2 ... real is short-hand notation for arg1 = sym('arg1','real'); arg2 = sym('arg2','real'); ...
SYMS arg1 arg2 ... positive is short-hand notation for
arg1 = sym('arg1','positive'); arg2 = sym('arg2','positive'); ...
SYMS arg1 arg2 ... unreal is short-hand notation for arg1 = sym('arg1','unreal'); arg2 = sym('arg2','unreal'); ...
Each input argument must begin with a letter and must contain only alphanumeric characters.
Examples:
syms x beta real is equivalent to: x = sym('x','real'); beta = sym('beta','real'); syms k positive is equivalent to: k = sym('k','positive');
To clear the symbolic objects x and beta of 'real' or 'positive' status, type syms x beta unreal
Como exemplo vamos usar as entidades simbólicas seguintes x, y, a, b e c.
>> clear
>> syms x y a b c f g >> whos
Name Size Bytes Class
a 1x1 126 sym object b 1x1 126 sym object c 1x1 126 sym object f 1x1 126 sym object g 1x1 126 sym object x 1x1 126 sym object y 1x1 126 sym object
Grand total is 14 elements using 882 bytes
Devemos notar que as variáveis são agora do tipo simbólico, em vez do tipo numérico de precisão dupla.
A instrução clear garante-nos que não temos quaisquer variáveis no nosso ambiente de trabalho.
Diferenciação
O uso da toolbox é muito útil para verificar cálculos realizados manualmente, ou mesmo para os
substituir. Para obter a sintaxe para a diferenciação simbólica deveremos fazer
>> help diff
DIFF Difference and approximate derivative.
DIFF(X), for a vector X, is [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)]. DIFF(X), for a matrix X, is the matrix of row differences,
[X(2:n,:) - X(1:n-1,:)].
DIFF(X), for an N-D array X, is the difference along the first non-singleton dimension of X.
DIFF(X,N) is the N-th order difference along the first non-singleton dimension (denote it by DIM). If N >= size(X,DIM), DIFF takes successive differences along the next non-singleton dimension. DIFF(X,N,DIM) is the Nth difference function along dimension DIM. If N >= size(X,DIM), DIFF returns an empty array.
Examples:
h = .001; x = 0:h:pi;
diff(sin(x.^2))/h is an approximation to 2*cos(x.^2).*x diff((1:10).^2) is 3:2:19
If X = [3 7 5 0 9 2]
then diff(X,1,1) is [-3 2 -3], diff(X,1,2) is [4 -2 9 -7],
diff(X,3,2) is the empty matrix.
Por exemplo, para encontrar o resultado de
dx
df
, onde f = e
-axx
3bsin(cx), e a, b e c são constantes não
especificadas, fazemos os seguintes passos.
>> clear >> syms a b c x >> f=exp(-a*x)*x^(3*b)*sin(c*x); >> diff_f = diff(f,x) diff_f = -a*exp(-a*x)*x^(3*b)*sin(c*x)+3*exp(-a*x)*x^(3*b)*b/x*sin(c*x)+exp(-a*x)*x^(3*b)*cos(c*x)*c
Devemos observar que o resultado é bastante complexo. Podemos usar o MatLab para o simplificar.
Para isso escrevemos
>> diff_f_simp = simple(diff_f)
diff_f_simp =
-exp(-a*x)*x^(3*b-1)*(a*sin(c*x)*x-3*b*sin(c*x)-cos(c*x)*c*x)
O MatLab usa diferentes algoritmos para concretizar a simplificação algébrica, escolhendo como
resposta final aquela que devolver o resultado mais curto.
Para obter a diferenciação de ordem superior, por exemplo,
2
2
dx
f
d
devemos fazer
>> diff2_f=diff(f,x,2) diff2_f = a^2*exp(-a*x)*x^(3*b)*sin(c*x)-6*a*exp(-a*x)*x^(3*b)*b/x*sin(c*x)-2*a*exp(- a*x)*x^(3*b)*cos(c*x)*c+9*exp(-a*x)*x^(3*b)*b^2/x^2*sin(c*x)-3*exp(-a*x)*x^(3*b)*b/x^2*sin(c*x)+6*exp(-a*x)*x^(3*b)*b/x*cos(c*x)*c-exp(-a*x)*x^(3*b)*sin(c*x)*c^2 Integrais indefinidos
Para obter a sintaxe da integração simbólica devemos fazer
>> help int
INT Integrate.
INT(S) is the indefinite integral of S with respect to its symbolic variable as defined by FINDSYM. S is a SYM (matrix or scalar). If S is a constant, the integral is with respect to 'x'.
INT(S,v) is the indefinite integral of S with respect to v. v is a scalar SYM.
INT(S,a,b) is the definite integral of S with respect to its symbolic variable from a to b. a and b are each double or symbolic scalars.
INT(S,v,a,b) is the definite integral of S with respect to v from a to b.
Examples:
syms x x1 alpha u t;
A = [cos(x*t),sin(x*t);-sin(x*t),cos(x*t)]; int(1/(1+x^2)) returns atan(x)
int(besselj(1,x),x) returns -besselj(0,x) int(x1*log(1+x1),0,1) returns 1/4
int(4*x*t,x,2,sin(t)) returns 2*sin(t)^2*t-8*t
int([exp(t),exp(alpha*t)]) returns [exp(t), 1/alpha*exp(alpha*t)] int(A,t) returns [sin(x*t)/x, -cos(x*t)/x] [cos(x*t)/x, sin(x*t)/x]
Por exemplo, para encontrar o integral indefinido int_g =
∫
gdx
, onde g = e
-axsin(cx), fazemos
>> clear >> syms a c x >> g=exp(-a*x)*sin(c*x); >> int_g = int(g,x) int_g = -c/(a^2+c^2)*exp(-a*x)*cos(c*x)-a/(a^2+c^2)*exp(-a*x)*sin(c*x
Podemos testar o resultado fazendo
>> diff_int = diff(int_g,x)
diff_int =
c^2/(a^2+c^2)*exp(-a*x)*sin(c*x)+a^2/(a^2+c^2)*exp(-a*x)*sin(c*x)
O resultado é diferente porque o MatLab nem sempre devolve o resultado na forma mais simplificada.
Neste caso podemos usar outra vez o comando de simplificação simple.
>> diff_int_simp = simple(diff_int)
diff_int_simp =
exp(-a*x)*sin(c*x)
O MatLab não introduz a constante de integração C, normalmente usada nos integrais indefinidos. Isto
fica a cargo do utilizador. Quando o MatLab não tem capacidade para integrar uma expressão representada
simbolicamente devolve um aviso.
Integais definidos
Para a definição do integral definido int_def_g =
∫
π
+
π
−
gdx
, onde g = e
-axsin(cx), devemos fazer o seguinte
>> clear >> syms a c x >> g = exp(-a*x)*sin(c*x); >> int_def_g = int(g,x,-pi,pi) int_def_g = -(c*cos(pi*c)+a*sin(pi*c)-exp(pi*a)^2*c*cos(pi*c)+exp(pi*a)^2*a*sin(pi*c))/exp(pi*a)/(a^2+c^2)
Quando o MatLab é incapaz de devolver uma solução analítica (simbólica) do integral, como no caso
>> int(exp(sin(x)),x,0,1)
Warning: Explicit integral could not be found. > In sym.int at 58
int(exp(sin(x)),x = 0 .. 1)
Devemos nestas situações encontrar a solução numérica usando o comando quad. Regra geral
devemos seguir os seguintes passos.
>> help quad
QUAD Numerically evaluate integral, adaptive Simpson quadrature. Q = QUAD(FUN,A,B) tries to approximate the integral of function FUN from A to B to within an error of 1.e-6 using recursive adaptive Simpson quadrature. The function Y = FUN(X) should accept a vector argument X and return a vector result Y, the integrand evaluated at each element of X.
Q = QUAD(FUN,A,B,TOL) uses an absolute error tolerance of TOL instead of the default, which is 1.e-6. Larger values of TOL result in fewer function evaluations and faster computation, but less accurate results. The QUAD function in MATLAB 5.3 used a less reliable algorithm and a default tolerance of 1.e-3.
[Q,FCNT] = QUAD(...) returns the number of function evaluations.
QUAD(FUN,A,B,TOL,TRACE) with non-zero TRACE shows the values of [fcnt a b-a Q] during the recursion.
QUAD(FUN,A,B,TOL,TRACE,P1,P2,...) provides for additional arguments P1, P2, ... to be passed directly to function FUN, FUN(X,P1,P2,...). Pass empty matrices for TOL or TRACE to use the default values.
Use array operators .*, ./ and .^ in the definition of FUN so that it can be evaluated with a vector argument.
Function QUADL may be more efficient with high accuracies and smooth integrands.
Example:
FUN can be specified as: An anonymous function: F = @(x) 1./(x.^3-2*x-5); Q = quad(F,0,2); A function handle: Q = quad(@myfun,0,2); where myfun.m is an M-file: function y = myfun(x) y = 1./(x.^3-2*x-5);
Class support for inputs A, B, and the output of FUN: float: double, single
See also quadv, quadl, dblquad, triplequad, @.
1.
criar a função que vai ser integrada no MatLab através do editor de texto e guardar no directório
corrente. Por exemplo, podemos criar um ficheiro com o nome func1.m.
function out = func1(x)
out = exp(sin(x));
quad('func1',0,1)
quad(@func1,0,1)
Conversão para uma variável do tipo numérico de dupla precisão
Por vezes o MatLab devolve resultados num formato simbólico, como por exemplo
>> clear >> syms x >> h=exp(-x)*sin(x) h = exp(-x)*sin(x) >> int_def_h=int(h,x,-pi,pi) int_def_h = -1/2*(-1+exp(pi)^2)/exp(pi)
Como podemos observar, o valor de π é retido no formato simbólico. Números irracionais podem
produzir o mesmo tipo de efeito. Para que o resultado possa ser usado em cálculos subsequentes, devemos
converter o resultado simbólico num valor numérico de dupla precisão. Para isso usamos o comando
double.
>> int_def_h_doub=double(int_def_h)
int_def_h_doub =
-11.5487
Substituição
Quando é necessário substituir um valor ou parâmetro por outro numa expressão devemos usar o
comando subs.
>> help sym/subs
SUBS Symbolic substitution. Also used to evaluate expressions numerically. SUBS(S) replaces all the variables in the symbolic expression S with values obtained from the calling function, or the MATLAB workspace.
SUBS(S,NEW) replaces the free symbolic variable in S with NEW. SUBS(S,OLD,NEW) replaces OLD with NEW in the symbolic expression S. OLD is a symbolic variable, a string representing a variable name, or a string (quoted) expression. NEW is a symbolic or numeric variable or expression. That is, SUBS(S,OLD,NEW) evaluates S at OLD = NEW.
of class DOUBLE.
If SUBS(S,OLD,NEW) does not change S, then SUBS(S,NEW,OLD) is tried. This provides backwards compatibility with previous versions and eliminates the need to remember the order of the arguments.
SUBS(S,OLD,NEW,0) does not switch the arguments if S does not change.
Examples: Single input:
Suppose a = 980 and C1 = 3 exist in the workspace. The statement
y = dsolve('Dy = -a*y') produces
y = exp(-a*t)*C1 Then the statement subs(y)
produces
ans = 3*exp(-980*t)
Por exemplo, imaginemos que pretendemos substituir a = 2 e c = 4 no resultado int_def_g. Isto é
conseguido fazendo.
>> clear >> syms a c x >> g = exp(-a*x)*sin(c*x); >> int_def_g = int(g,x,-pi,pi) int_def_g = -(c*cos(pi*c)+a*sin(pi*c)-exp(pi*a)^2*c*cos(pi*c)+exp(pi*a)^2*a*sin(pi*c))/exp(pi*a)/(a^2+c^2) >> int_sub=subs(int_def_g,{a,c},{2,4}) int_sub = 107.0980
Solução de equações diferenciais
A toolbox symbolic do MatLab é capaz de resolver muitos tipos diferentes de equações, incluindo não
lineares e sistemas de equações. Para isso usa o comando solve.
>> help sym/solve
SOLVE Find the zeros of symbolic expressions. SOLVE(expr1,expr2,...,exprN,var1,var2,...varN) or
SOLVE(expr1,expr2,...,exprN) finds zeros of symbolic expressions.
The exprs are symbolic expressions. The vars are symbolic variables or strings specifying the unknown variables. SOLVE seeks zeros of the expressions. If not specified, the unknowns are determined by FINDSYM. If no analytical zero is found and the number of expressions equals the number of dependent variables, a numeric solution is attempted.
Three different types of output are possible. For one expression and one output, the resulting zero is returned, with multiple zeros in a symbolic vector. For several equations and an equal number of outputs, the results are sorted in lexicographic order and assigned to the outputs. For several equations and a single output, a structure containing the zeros is returned.
Examples: Zeros of a polynomial: solve(x^2-x-6) returns ans = [ -2] [ 3]
Devemos seguir os seguintes passos para resolver uma ou mais equações.
1.
definir as variáveis na equação usando o comando syms;
2.
definir a equação;
3.
resolver a equação usando o comando solve;
4.
se existir mais do que uma equação, devemos ver qual deve ser escolhida em função do tipo de
problema;
5.
confirmar o resultado efectuando a sua substituição na equação.
O seguinte exemplo pode ajudar a compreender melhor o comando. Pretende-se encontrar a solução
para seguinte equação quadrática ax
2+ bx + c = 0.
>> clear >> syms x y z a b c >> eq = 'a*x^2+b*x+c = 0'; >> [x]=solve(eq,x) x = 1/2/a*(-b+(b^2-4*a*c)^(1/2)) 1/2/a*(-b-(b^2-4*a*c)^(1/2))