Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Especialidad
Matlab
I II III IV Fundamentos Programacin Simulink Matlab/Simulink
2
Fundamentos
Qu es MatLab?
MATLAB proviene de "Matrix Laboratory" y es un
El entorno de desarrollo. Variables. Tipos. Operadores aritmticos, lgicos y relacionales. Creacin de vectores y matrices. Manipulacin de matrices. Uso de funciones predefinidas. Funciones usadas en teora de control (Objetos simblicos,
software de computacin numrica y lenguaje de programacin desarrollado por The MathWorks, Inc.
MATLAB permite manipulacin de matrices, plotting
de functiones y datos, implementacin de algoritmos, creacin de interfaces de usuario, e interfazamiento con programas escritos en otros languages, incluyendo C, C++, y Fortran.
4/30/2012
Simulink
It is an additional package which adds graphical
multi-domain simulation and Model-Based Design for dynamic and embedded systems.
Variables
Nombres de variables
Letras seguida de nmeros o subrayados Hasta 31 characters Es sensitiva a maycula y mincula No se requiere declaration de tipo o dimensin Ejemplo: >> velocity_rpm = 5400 Integers Real Complex : : : 5400, -88 0.0015, 1.5e-3, pi 3i, 5.4j, 3.1e5j, 5 6i
7
Caracteres o cadenas
Definicin de variables
Variables lgicas
4/30/2012
Operadores de Matrices
Arithmetic
+ * .* (For arrays) (# columnas M1 = # filas M2) Division / ./ (For arrays) Left Division (Matrix) \ .\ (For arrays) Power ^ .^ (For arrays) Complex conjugate transpose Specify evaluation order ()
9
Roberto Tantalean 2012
10
Operadores
Lgicos
AND OR NOT
& | ~
Relacionales
>> t= 0:5 Resultado: t = 0 1 2 3 4 5 >> t= 0:0.1:5 Resultado: t = 0 0.1 0.2 0.3 4.9 5.0 Se usa para referirse a un elemento de una matriz:
> t(4) > y(:, 4) Lista todos los elementos de la 4ta columna.
11
12
4/30/2012
Matrices
Es un arreglo rectangular de elementos (numbers) Formas de entrar matrices: Forma explcita:
> > matrix_1 = [1 2 3 4; 4 5 6 8; 8 9 10 11]
operacin.
Se usa para separar filas en el ingreso de matrices.
>> load E:\data.dat Se necesita tener un archivo ASCII llamado data.dat con los nmeros. La variable (matriz) data ser creada.
Usando funciones built-in (zeroes(2,4), ones(3,4), rand(2,4)) Usando funciones creadas en M-files
Roberto Tantalean 2012
13
14
Vectores
Son matrices de solo una fila o columna Otras formas de generar vectores: Linspace: linspace(a, b, n), Desde a hasta b con n
Example of Matrices
>> A = [2 7 6; 9 0 5; 3 0.5 6]; >> B = [8 7 0; 3 2 5; 4 -1 7]; >> ones[3,7] >> rand[4,8] >> A == B
puntos. >> x = linspace(-1, 10, 12) Logspace: logspace(g, h, n), Desde 10g hasta 10h con n puntos. >> x = logspace(-1, 2, 4) x= 0.10 1.00 10.00 100.00
Roberto Tantalean 2012
15
16
4/30/2012
diagonales de la matriz)
>> diag(A)
Roberto Tantalean 2012
18
Funciones
Built-in
Built-in Functions
Funciones desarrolladas y precompiladas por Matlab como programas ejecutables. Por ejemplo: >> sum(A)
Definidas por el Usuario
19
20
4/30/2012
Math Functions
exp(x)
Funciones Grficas
ezplot () plot () semilogx() semilogy() loglog()
Encuentra races de polinomios -> Soluciona Ec. Dif. (ODE: Ordinary Differential Equation)
21
Roberto Tantalean 2012
->
22
Objetos Simblicos
syms :
Syntaxis: construye un objeto simblico
Example 3
Find the Laplace of the function: SOLUTION:
f (t ) 2sin(3t )
23
24
4/30/2012
25
26
Ia)
Funciones
27
28
4/30/2012
programa, usar exist. The exist function returns a number identifying the source. If the source is a file with an .m file extension, then exist returns the number 2. For example for the repmat (replicate and tile an array):
>> exist repmat ans = 2
29
30
Funciones de Comandos
Tambien llamadas Funciones Annimas.
Consiste de un simple comando de MATLAB que puede
ejecucin, o
En un archivo (Script) guardado en un lugar de
almacenamiento permanente.
>> ManejadorFuncin =
@(ListaArgumentos)
expresin
31
32
4/30/2012
Ejemplo:
Crear una funcin annima que calcule el cuadrado de un nmero. SOLUCION:
Ejercicio:
Crear el manejador de funcin: r = sin(x) + cos(x) Solution:
r = @(x)(sin(x)+cos(x));
33
34
Ejercicio:
Crear el manejador de funcin: r = sin(x) + cos(y) Solution:
r = @(x, y)(sin(x)+cos(y));
Subfunciones.
35
36
4/30/2012
Funciones Primarias
Formato: (Nombre archivo/Script: nombrefuncion.m): Son visibles a otras funciones desarrolladas en archivos
function [VariablesSalida] = nombrefuncion(VariablesEntrada) % Comentarios. Instrucciones; VariableSalida1 = instruccin; VariableSalidaN = instruccin; end
comas.
Pueden ser escalares, vectores, matrices o cadenas de
Roberto Tantalean 2012
37
texto.
38
Ejemplo:
La funcin promedio reside en el archivo promedio.m:
Ejemplo:
Convertir coordenadas Cartesianas a coordinadas
polares.
Solution:
En el archivo: cartesiana_polar.m function [r, theta] = cartesiana_polar(x, y) r = sqrt(x^2 + y^2); theta = atan2(y,x);
end
Se puede invocar esta funcin desde el comando de MATLAB para encontar el promedio de tres valores: >> promedio ( [12 60 42] )
Roberto Tantalean 2012
40
10
4/30/2012
Funciones Anidadas
Formato: (Nombre archivo/Script: nombrefuncion.m):
function [VariablesSalida] = nombrefuncion(VariablesEntrada) % Comentarios. Instrucciones; function [VarsSal] = nombrefuncionanidada(VarsEnt) VarSal = instruccin; end VariableSalida = instruccin; end
Roberto Tantalean 2012
Ejemplo:
Crear una funcion para obtener un manejador de la
funcin cbica.
Solution: function h = ObtenerManejadorCubo h = @encontrarCubo; function cubo = encontrarCubo(x) cubo = x.^3; end end >> elevarCubo = ObtenerManejadorCubo; >> elevarCubo(5)
Roberto Tantalean 2012
41
42
43
44
11
4/30/2012
Leer Archivos
fread : Leer datos de un archivo binario
fwrite(fileID, A) Escribe los elementos del vector A a un archivo binario (fileID) en orden de columnas. fwrite(fileID, A, precision) traduce los valores de A de acuerdo a la forma y tamao descrita por la the precision.
A = fread(fileID) fread(fileID) lee datos de un archivo binario, los ubica en la columna del vector A y posiciona el puntero al final del archivo. A = fread(fileID, sizeA) fread(fileID, sizeA) reads sizeA elements into A and positions the file pointer after the last element read. sizeA can be an integer, or can have the form [m,n]
45
Roberto Tantalean 2012
46
47
48
12
4/30/2012
Ejemplo:
Escritura: >> h = 12.50; >> fout = fopen(output.dat', 'w'); >> fprintf(fout, '%f', h); >> fclose(fout); Lectura: >> fin = fopen(output.dat', r'); >> h = fscanf(fin, '%f'); >> fclose(fin);
Roberto Tantalean 2012
Grficos
Plotting (2D and 3D) Mesh and Surfaces Images Handle Graphics
49
50
Plotting (Grfica)
Existen dos formas de crear grficos: Desde la Lnea de Comandos (>>) Usando Plotting tools Con la funcin de lnea de Comando:
Opciones de Plot
La funcin plot(X, Y, S) grafica los smbolos y colores
donde S es una cadena de caracteres conformada por uno de los siguientes elementos:
b blue . point solid
>> plot(X, Y)
Grafica el vector Y versus el vector X. Si X o Y es una matriz, entonces el vector es graficado versus la fila o columnas de la matriz, cualquiera que concuerda.
>> plot(Y) grafica las columnas de Y versus su ndice. Si Y es complejo, PLOT(Y) es equivalente a PLOT(real(Y), imag(Y)). En todos los otros usos de PLOT, la parte imaginaria se ignora.
Roberto Tantalean 2012
o circle : dotted x x-mark -. dashdot + plus -- dashed * star (none) no line s square d diamond v ^ < > triangle (down, up , etc) p pentagram h hexagram
52
51
13
4/30/2012
Plotting Mltiple
plot(X1, Y1, S1, X2, Y2, S2, X3, Y3, S3, ..., , )
Combina las grficas defindas por el triplete (X, Y, S), donde las X's e Y's son vectores o matrices y las S's son cadenas.
Example 1:
Graficar la funcin: y = tan(sin(x)) sin(tan(x)
53
54
Example 2:
Display the continue line and the steam in the function y(t) = esin(t)
55
56
14
4/30/2012
57
58
Editando Lineas
Usando >>plottools
59
60
15
4/30/2012
Save the graph as a FIG-file (select Save from the figure File menu). Generar el cdido MATLAB Este cdigo puede re-crear el grfico (select Generate M-File from the figure File menu).
Roberto Tantalean 2012
61
62
Mesh Example:
Graficar la funcin bi-dimensional seno, z = sin(R)/R,
centro de la matriz
R x2 y 2
Adicionado eps (a MATLAB command that returns a small floating-point number) evita el valor
63
64
16
4/30/2012
Mesh Example:
>> [x,y] = meshgrid(-8:.5:8); >> R = sqrt(x.^2 + y.^2) + eps; >> z = sin(R)./R; >> mesh(x,y,z)
Surface Example:
>> surf(x,y,z)
65
66
Surface Example:
>> surf(x,y,z)
67
68
17
4/30/2012
Solucin Simblica
>> dsolve(...) Acepta ecuaciones simblicas que representan ecuaciones diferenciales ordinariasu sus condiciones iniciales.
dsolve(eqn1, eqn2, )
Por defecto, la variable independiente es 't. La letra 'D' denota differenciacin con respecto a la variable independiente (d ?/dt). Una "D" seguida de un digito denota diferenciacin repeatida: D2 es d2 ?/dt2.
69
70
Example:
Resolver:
Example:
dx 7 x dt
Solve:
dx 7 x dt
Given
x(O) = 1
71
72
18
4/30/2012
Ejemplo:
dTP (t ) K1 TP (t ) TG (t ) dt dTG (t ) K 2 TP (t ) TG (t ) dt
Donde K1 = 2.5 y K2 = 1.2
TP (0) 370 TG (0) 300
T=
73
74
the results are sorted in lexicographic order and assigned to the outputs.
For several equations and a single output, a structure
75
76
19
4/30/2012
Example:
Resolver: 7 sin(x) = 10
Example:
Solve:
x2 + xy + y = 3 x2 4x +3 = 0
77
78
Solucin Numrica
dy1 f1 ( x, y1 ,, ym ) dx dym f m ( x, y1 ,, ym ) dx y1 ( x0 ) y10 ym ( x0 ) ym 0 dy f ( x, y ) y ( x0 ) y 0 dx
Problems Nonstiff ODEs Nonstiff ODEs Nonstiff ODEs Stiff ODEs Stiff ODEs Moderately stiff ODEs Stiff ODEs Implicit ODEs
Method Runge-Kutta Runge-Kutta Adams-Bashforth Numerical differentiation Rosenbrock Trapezoidal Trapezoidal & numerical differentiation Numerical differentiation
Argumentos
odefun: Es una manejador de funcin que evalua el lado derecho de la ecuacin diferencial de la forma y = f(t, y)
Roberto Tantalean 2012
80
20
4/30/2012
Ejemplo ode45:
tspan: Es un vector que especifica el intrvalo de
integracin [t0,tf].
y0 : Vector de condiciones initiales para y Options : Optional integration argument created using the
Solucin:
odeset function.
Argumentos de salida:
T : Vector de columna de los puntos del tiempo. Y : Vector de las soluciones. Each row in y corresponds to the solution at a time returned in the corresponding row of t.
Roberto Tantalean 2012
81
82
83
84
21
4/30/2012
II
El Lenguaje de Programacin Cracin de M-files (Script and functions) Estructuras de Control de Flujos ( if, for,
Programacin
files).
Aplicaciones
Roberto Tantalean 2012
85
86
El Lenguaje de Programacin
Los programs MATLAB son secuencias de
Scripts
Script es una coleccin de instrucciones de MATLAB
en el commando de Matlab.
El archivo m debe estar visible al usuario (Be sure
that MATLAB's internal path variable is set to the direction containing the script).
87
88
22
4/30/2012
textos.
From menu: File -> New > Script or Ctrl-N Para guardar todos los comandos en una sesin de
Script operan solamente en las variable codificadas en el archivo m. Functions are more suitable for general purpose tasks that will be applied to different data. Scripts are useful for tasks that don't change. Un script es como una macro, por lo tanto todas las variables creadas en el script son adicionadas al workspace de la sesin en curso.
89
Roberto Tantalean 2012
90
que en el workspace, los valores de estas son cambiadas por las aciones del script.
En contraste, las variables de las funciones son locales
Conditional Control If, else Switch Loop Control for while continue break Error Control try catch
91
Roberto Tantalean 2012
a la funcin. (The exception is that it's possible to declare and use global variables). El alcance local de las variables de una funcin brinda mas seguridad y flexibilidad.
92
23
4/30/2012
If-elseif-else-end
if CONDICION INSTRUCCIONES elseif CONDICION INSTRUCCIONES else INSTRUCCIONES end
Ejemplo
Traducir C to Matlab:
93
94
La Funccin rem()
Calcula el remanente (resto) de una divisin.
Example:
Ejecutar la funciones previamente desarrolladas magic1,
>> rem(x, y)
The inputs x and y must be real arrays of the same
magic2, and magic3 para cada uno de los tres casos: cuando n es impar, cuando n es par pero no divisible por 4, o cuando n es divisible por 4.
Solution:
96
24
4/30/2012
Switch
Ejecuta un grupo de instrucciones basadas en el valor
97
switch VARIABLE_EXPRESION case VALOR1 INSTRUCCIONES case VALOR2 INSTRUCCIONES case VALORn INSTRUCCIONES otherwise INSTRUCCIONES end Roberto Tantalean 2012
98
Example:
Execute a function magic1, magic2, and magic3 for three
El Lazo: For-End
Repite un grupo de instrucciones un nmero
different cases: when n is odd (impar), when n is even (par) but not divisible by 4, or when n is divisible by 4. Solution: switch (rem(n,4)==0) + (rem(n,2)==0) case 0 % Impar magic1(n) case 1 % Par no divisible por 4 magic2(n) case 2 % Divisible por 4 magic3(n) otherwise error('This is impossible') end
Roberto Tantalean 2012
99
100
25
4/30/2012
Ejemplo:
Crear un vector de 30 elementos (
El Lazo: While-End
n2+3)
Repite un grupo de instrucciones un nmero
especially when they are nested: for i = 1:m for j = 1:n H(i,j) = 1/(i+j); end end
Roberto Tantalean 2012
101
102
Example: While-End
Aplicar el mtodo de interval bisection para
103
104
26
4/30/2012
Continue
Continue passes control to the next iteration of the for
Try
The statements in the try block
or while loop in which it appears, skipping any remaining statements in the body of the loop.
Example:
Shows a continue loop that counts the lines of code in the file magic.m, obviando las lneas en blanco y los comentarios. Se usa el comando continue para avanzar a la siguiente linea del archivo magic.m sin incrementar el contador
(whenever a blank line or comment line is encountered)
Roberto Tantalean 2012
(between try and catch) execute just like any other program code. If an error occurs within the try section the statements between catch and end are then executed. Examine the contents of the MException object exceptObj to see the cause of the error. If an error occurs between catch and end, MATLAB terminates execution unless another try-catch sequence has been established.
Roberto Tantalean 2012
105
106
tiene su propio function workspace el que se mantiene separado del base workspace and y de otros function workspaces.
Incluso subfunctions definidas en el mismo archivo
107
108
27
4/30/2012
Variables Locales
Local are those variables stored in a function
Variables Globales
Si se desea que mas de una funcin compartan una
misma variable: declarar la variable como global en todas las funciones. Declarar tambien en la lnea de commandos si quiere accesar la variable desde el base workspace . La declaracin global debe ocurrir antes que la variable sea usada en una funcin. Se sugiere usar letras maysculas como nombres de variables globales.
109
110
Crear la function en el archivo falling.m: function h = falling(t) global GRAVITY h = 1/2*GRAVITY*t.^2; end Ejecucin: >> global GRAVITY >> GRAVITY = 32; >> y = falling((0:.1:5)');
Roberto Tantalean 2012
111
112
28
4/30/2012
113
114
115
116
29
4/30/2012
Ejemplo:
Preparar el script Respuesta1erOrden.m para deployment fuera del ambiente de MATLAB. Generar los archivos C or C++ y producir el archivo binario standalone exe. Soilucin: >> mcc -m Respuesta1erOrden.m Select a compiler: [0] c++ [1] none Compiler:
117
Roberto Tantalean 2012
118
Simulacin
Simulink
Roberto Tantalean 2012
119
120
30
4/30/2012
122
subroutines from the MATLAB command line as if they were built-in functions. For example, you can:
Call preexisting C/C++ and Fortran programs from
MATLAB without having to rewrite them as MATLAB functions. Code bottleneck computations that do not run fast enough in MATLAB. The mxArray access library creates and manipulates MATLAB arrays. The mex library performs operations in the MATLAB environment.
Roberto Tantalean 2012
interpreter with Java commands and to create and access Java objects. For example, you can:
Access Java API class packages that support I/O and
123
networking. Access third-party Java classes. Construct Java objects in MATLAB. Call Java methods, using either Java or MATLAB syntax. Pass data between MATLAB variables and Java objects.
124
31
4/30/2012
Matlab
I II III IV V
Roberto Tantalean 2012
Simulink
Matlab Real-time
125
32