Está en la página 1de 32

4/30/2012

Especialidad

: Ingeniera de Control y Automatizacin

Matlab
I II III IV Fundamentos Programacin Simulink Matlab/Simulink
2

Breve Introduccin a Matlab


Profesor : Dr. Ing. Roberto Z. Tantalen C.
Process Control Engineer Ph.D. from University of Louisville, KY, EEUU

Roberto Tantalean 2012

Roberto Tantalean 2012

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

Laplace, poles y ceros, Routh, Lugares geomtricos, Node y Nyquist).

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.

Roberto Tantalean 2012

Roberto Tantalean 2012

4/30/2012

Simulink
It is an additional package which adds graphical

multi-domain simulation and Model-Based Design for dynamic and embedded systems.

Roberto Tantalean 2012

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

Letra = A Cadena = texto Rpta = true Rpta = false Devuelve: 1 Devuelve: 0

Definicin de variables

Variables lgicas

Nmeros (Rango: formato largo - 10-308, 10+308)


Roberto Tantalean 2012

Roberto Tantalean 2012

4/30/2012

Operadores de Matrices
Arithmetic

Addition Subtraction Multiplication

+ * .* (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

Roberto Tantalean 2012

10

Operadores
Lgicos

El Operator dos puntos (:)


For example: if(A & B)

AND OR NOT

& | ~

Se usa para crear vectores:

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.

Mayor que Menor que Igual a Diferente a

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

Roberto Tantalean 2012

11

Roberto Tantalean 2012

12

4/30/2012

El Operator Punto y Coma (;)


Se usa para no mostrar los resultados de una

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.

Usando un archivo externo

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

Roberto Tantalean 2012

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

Roberto Tantalean 2012

16

4/30/2012

Operaciones con Matrices


Sumatoria (Suma cada columna) >> sum(A) When you dont use any variable to store the output, Matlab will use the variable ans Transpuesta >> A >>sum(A) (Suma de cada fila) Diagonal (Obtiene un nuevo vector con los elementos

Trabajando con Matrices


Subscript Formato: MATRIX(i, j) >> B(2,3) Concatenacin >> B = [A A]

(Une la matriz A con otra matriz A) (Deben tener = # de filas)

diagonales de la matriz)
>> diag(A)
Roberto Tantalean 2012

Eliminando Filas/Columnas Formato: = [] >> B(:,2) = [] (Elimina la segunda columa de la matriz B)


17
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

Desarrolladas por el usuario e implementadas como programas.

Roberto Tantalean 2012

19

Roberto Tantalean 2012

20

4/30/2012

Math Functions
exp(x)

Funciones Grficas
ezplot () plot () semilogx() semilogy() loglog()

-> ex sqrt(x) -> x sin(x), cos(x), tan(x) log(x) log10(x)


roots()

ode45, ode23 , ode113

Encuentra races de polinomios -> Soluciona Ec. Dif. (ODE: Ordinary Differential Equation)
21
Roberto Tantalean 2012

->

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 )

syms arg1 arg2 ...


Lo mismo se puede escribir como >> arg1 = sym('arg1'); >> arg2 = sym('arg2'); Para remover un objecto de la memoria:

>> f = 2*sin(3*t) >> ezplot(f )

syms arg1 arg2 clear


Roberto Tantalean 2012

23

Roberto Tantalean 2012

24

4/30/2012

>> F = laplace(f ) >> ezplot(F)

Roberto Tantalean 2012

25

Roberto Tantalean 2012

26

Ia)

Funciones

Porgramas fuentes de funciones.


En el subfolder de toolbox\matlab, se puede

Funciones Definidas por el Usuario

encontrar los fuentes de muchas funciones proveidas con MATLAB.


>> dir ( [matlabroot '\toolbox\matlab\'] )

Cualquier funcin que escriba en MATLAB es como

cualquier otra funcin codificada con MATLAB.


Cuando se invoca a una de estas funciones, MATLAB

entiende y ejecuta cada lnea de cdigo en el archivo.


Roberto Tantalean 2012

27

Roberto Tantalean 2012

28

4/30/2012

Existe la funcin en Matlab?


Para encontrar si una function es implementada con un

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

Viewing the Source Code


To find the source code for any MATLAB function, use

which. For example:


>> which repmat
D:\matlabR14\toolbox\matlab\elmat\repmat.m

Roberto Tantalean 2012

29

Roberto Tantalean 2012

30

Como Crear Funciones


Existen dos formas de crear una nueva funcin:
En un comando ingresado al tiempo de

Funciones de Comandos
Tambien llamadas Funciones Annimas.
Consiste de un simple comando de MATLAB que puede

interactuar con mltiples argumentos de entradas y salidas.


La sintsis para crear una funcin annima is

ejecucin, o
En un archivo (Script) guardado en un lugar de

almacenamiento permanente.

>> ManejadorFuncin =

@(ListaArgumentos)

expresin

Roberto Tantalean 2012

31

Roberto Tantalean 2012

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:

>> sqr = @(x) x.^2;


Cuando se ejecuta esta funcin, MATLAB asigna el valor que se pasa en la variable x, y luego usa x en la ecuacin x.^2. El operador @ construye un manejador para esta funcin y asigna el manejador a la variable de salida sqr.
Roberto Tantalean 2012

r = @(x)(sin(x)+cos(x));

33

Roberto Tantalean 2012

34

Ejercicio:
Crear el manejador de funcin: r = sin(x) + cos(y) Solution:

Funciones Guardades en Archivo


Existen varios tipos que se pueden escribir y

ejecutar desde un archivo. Los mas bsicos son:


Funciones Primarias, y

r = @(x, y)(sin(x)+cos(y));

Subfunciones.

El nombre de la funcin es precisamente el

nombre del archivo.


Roberto Tantalean 2012

35

Roberto Tantalean 2012

36

4/30/2012

Funciones Primarias
Formato: (Nombre archivo/Script: nombrefuncion.m): Son visibles a otras funciones desarrolladas en archivos

externos, al contrario de las subfunciones.


Pueden ser llamadas desde una funcin annima. Pueden ser llamadas desde la linea de comandos de

Matlab o desde otra funcion.

function [VariablesSalida] = nombrefuncion(VariablesEntrada) % Comentarios. Instrucciones; VariableSalida1 = instruccin; VariableSalidaN = instruccin; end

VariablesEntrada y Salida deben estar separadas por

comas.
Pueden ser escalares, vectores, matrices o cadenas de
Roberto Tantalean 2012

37

Roberto Tantalean 2012

texto.

38

Ejemplo:
La funcin promedio reside en el archivo promedio.m:

Ejemplo:
Convertir coordenadas Cartesianas a coordinadas

---------------------------------------function y = promedio(x) % Promedio de los elementos de un vector. y = sum(x)/length(x); end


--------------------------------------------------

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

>> [radio, angulo] = cartesiana_polar( 20, 10)


39
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

Operationes Comunes con Archivos


Manipulacin de Archivos Grficos Soluciones Numricas Algebra Lineal Resolucion Ecuaciones Diferencales Control Toolbox Read (Leer) Write (Escribir) Import (Importar) Export (Exportar)

Roberto Tantalean 2012

43

Roberto Tantalean 2012

44

11

4/30/2012

Crear Archivos Binarios


fwrite : Escribe datos en un archivo binario

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

Roberto Tantalean 2012

46

Ejemplo: Crear y leer un archivo


>> % Aqui se crea el archivo binario magic5.bin >> fid = fopen('magic5.bin', 'w'); >> fwrite(fid, magic(5)); >> fclose(fid); >> % Aqui se lee el contenido del vector almacenado en el archivo magic5.bin >> fid = fopen('magic5.bin'); >> m5 = fread(fid, [5, 5], '*uint8'); >> fclose(fid);
Roberto Tantalean 2012

Crear un Archivo Texto


>> fprintf(fileID, format, A, ...) Donde format se aplica a todos los elementos del vector A >> txt_str = texto/datos para archivo; >> fid = fopen(output.dat','w'); >> fprintf(fid, '%s', txt_str); >> fclose(fid);

47

Roberto Tantalean 2012

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

Roberto Tantalean 2012

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

g green r red c cyan m magenta y yellow k black w white

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

Roberto Tantalean 2012

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)

plotyy(X1, Y1, X2, Y2, plot1, plot2, , )

plot1 = plot plot2 = steam


Roberto Tantalean 2012

53

Roberto Tantalean 2012

54

Plot con opciones:

Example 2:
Display the continue line and the steam in the function y(t) = esin(t)

Roberto Tantalean 2012

55

Roberto Tantalean 2012

56

14

4/30/2012

Edit -> Figure Properties


Ubicando Grficos en una Figura

Roberto Tantalean 2012

57

Roberto Tantalean 2012

58

Editando Lineas

Usando >>plottools

Roberto Tantalean 2012

59

Roberto Tantalean 2012

60

15

4/30/2012

Adicionando Datos a Grficos

Guardando Grficos para Recuperarlos enMATLAB


Existen dos formas que permiten continuar con la

edicin del grfico:


Guardar como archivo FIG

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

Roberto Tantalean 2012

62

Mallas (Mesh) y Superficies


Muestra una funcin de dos variables: z = f(x, y) Mesh (malla) produce una superficie de mallas de

Mesh Example:
Graficar la funcin bi-dimensional seno, z = sin(R)/R,

entre las direciones de x e y.


Donde R es la distancia del origen, el cual esta al

colores cuyas lneas conecta los puntos definidos.


Surface (surf ) muestra ambos las lneas de coneccin y

centro de la matriz

R x2 y 2

las caras de la superficie en determinado color.

Adicionado eps (a MATLAB command that returns a small floating-point number) evita el valor

indeterminado O/O en el origen.

Roberto Tantalean 2012

63

Roberto Tantalean 2012

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)

Roberto Tantalean 2012

65

Roberto Tantalean 2012

66

Surface Example:
>> surf(x,y,z)

Solucin de Ecuaciones Diferenciales


Analytical Solution(Symbolic) Numerical Solution

Roberto Tantalean 2012

67

Roberto Tantalean 2012

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.

Roberto Tantalean 2012

69

Roberto Tantalean 2012

70

Example:
Resolver:

Example:
dx 7 x dt
Solve:

dx 7 x dt

Given

x(O) = 1

Roberto Tantalean 2012

71

Roberto Tantalean 2012

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=

Roberto Tantalean 2012

73

Roberto Tantalean 2012

74

solve(eqn1, eqn2, , eqnN)


Three different types of outputs are possible:
For one equation and one output, the resulting solution

is returned with multiple solutions to a nonlinear equation 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 solutions is returned.


Roberto Tantalean 2012

75

Roberto Tantalean 2012

76

19

4/30/2012

Example:
Resolver: 7 sin(x) = 10

Example:
Solve:

x2 + xy + y = 3 x2 4x +3 = 0

Roberto Tantalean 2012

77

Roberto Tantalean 2012

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

Solucin Numrica (ode45)


Resuelve problemas de valor inicial en EDO. Sintxis >> [T, Y] = ode45(odefun, tspan, y0) >> [T, Y] = ode45(odefun, tspan, y0, options)

Solver ode45 ode23 ode113 ode15s ode23s ode23t ode23tb ode15i

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

Roberto Tantalean 2012

82

Roberto Tantalean 2012

83

Roberto Tantalean 2012

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

while, switch-case, continue and break ).

Variables locales and Globales Debugging/Depuracin Programas in Lenguaje C (MEX executable

files).

Aplicaciones
Roberto Tantalean 2012

85

Roberto Tantalean 2012

86

El Lenguaje de Programacin
Los programs MATLAB son secuencias de

Scripts
Script es una coleccin de instrucciones de MATLAB

comandos de Matlab guardados en un archivo texto con extensin .m.


Existen dos tipos de programas en MATLAB:
Scripts and Functions.

guardados en un archivo texto con un nombre (.m).


Para ejecutarlo se escribe el nombre del archivo script

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

Roberto Tantalean 2012

87

Roberto Tantalean 2012

88

22

4/30/2012

Creando a script m-file


Scripts tambien se pueden crear con un simple editor de

Scripts versus Funciones


Scripts contienen solo instrucciones de MATLAB.

textos.
From menu: File -> New > Script or Ctrl-N Para guardar todos los comandos en una sesin de

``Functions'' son mas que instrucciones.


Funciones tienen parmetros de entrada y salida.

Matlab usar: >> diary nombre del archivo.

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

Roberto Tantalean 2012

90

Control del Flujo


Si alguna variable en un script tiene el mismo nombre

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.

Roberto Tantalean 2012

92

23

4/30/2012

If-elseif-else-end
if CONDICION INSTRUCCIONES elseif CONDICION INSTRUCCIONES else INSTRUCCIONES end

Ejemplo
Traducir C to Matlab:

Roberto Tantalean 2012

93

Roberto Tantalean 2012

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:

size, or real scalars. >> rem(6, 2) ans = 0 >> rem(7, 2) and= 1

if rem(n, 2) ~= 0 magic1(n) elseif rem(n, 4) ~= 0 magic2(n) else magic3(n) end


95
Roberto Tantalean 2012

Roberto Tantalean 2012

96

24

4/30/2012

Switch
Ejecuta un grupo de instrucciones basadas en el valor

de una variable o expresin.

Roberto Tantalean 2012

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

predeterminado de veces. for INDICE = RANGO INSTRUCCIONES end

99

Roberto Tantalean 2012

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

for n = 1:30 r(n) = n^2 + 3; end


It is a good idea to indent the loops for readability,

indefinido de veces segn la condicin de trmino. while CONDICION INSTRUCCIONES end

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

Roberto Tantalean 2012

102

Example: While-End
Aplicar el mtodo de interval bisection para

encontrar el cero de una funcin polinmica como: f(x) = x3 - 2x 5


Solucin:

Asumir que la raiz se encuentra entre 0 y 3.

Roberto Tantalean 2012

103

Roberto Tantalean 2012

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

Variables Locales y Globales


MATLAB guarda las variables en una parte de la memoria

Alcance de las Variables Locales y Globales

llamado workspace el que es de dos tipos.


La Base workspace guarda las variables creadas en una

sessin de comandos o por la ejecucin de un script.


Las functions no usan el base workspace. Cada function

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

tiene separada su function workspace.


Roberto Tantalean 2012

107

Roberto Tantalean 2012

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

workspace and it can be call only by the own function or m-file.


Puede haber mas de una variable con el mismo

nombre pero en diferentes function workspaces.

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.

Roberto Tantalean 2012

109

Roberto Tantalean 2012

110

Ejemplo de Variables Globales


Crear un programa para determinar la cada libre de un

Ejemplo: Respuesta Modelo 1er. Orden

cuerpo debido a la gravedad.


Solution:

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

Roberto Tantalean 2012

112

28

4/30/2012

Roberto Tantalean 2012

113

Roberto Tantalean 2012

114

Roberto Tantalean 2012

115

Roberto Tantalean 2012

116

29

4/30/2012

Creando Programas EXE


mcc: MATLAB invoca al compilador C/C++ (Ver 4.11). >> mcc [-options] programa [programa2 ...] >> mcc -? NombreArchivo.m Donde ? es una directiva (p.e. m = ejecutable C++ standalone)

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

Roberto Tantalean 2012

118

Simulacin

Simulink
Roberto Tantalean 2012

119

Roberto Tantalean 2012

120

30

4/30/2012

Interfazamiento con otros Lenguajes de Programacin


Matlab can work with the following languages:
C Fortran Java Maple

Invocar a MATLAB desde Programas C/C++ y Fortran


Use the MATLAB engine library to call MATLAB from

C/C++ and Fortran programs.


When you call MATLAB from your own C/Fortran

programs, MATLAB acts as a computation engine.


For example, you can: Use MATLAB as a programmable mathematical subroutine library. Build an application with a front end (GUI) programmed in C/C++ and a back end (analysis) programmed in MATLAB.
121
Roberto Tantalean 2012

And with libraries made in other languages in the

form of: DLL (Dynamic Linked Library)


Roberto Tantalean 2012

122

Invocar a Programas C/C++ y Fortran desde MATLAB


Use MEX-files to call your own C/C++ or Fortran

Invocar a Java desde MATLAB


Every installation of MATLAB software includes Java

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

Virtual Machine (JVM) software.


The JVM software allows you to use the MATLAB

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

Roberto Tantalean 2012

31

4/30/2012

Matlab
I II III IV V
Roberto Tantalean 2012

Basics Control and Signal Processing Toolbox Programming

Simulink
Matlab Real-time
125

32

También podría gustarte