You are on page 1of 27

Laboratory Session # 1.

Getting Started with the MATLAB Simulation Environment

Sesin de Laboratorio No. 1 Iniciando en el Ambiente de Simulacin de MATLAB

English

Laboratory Session # 1.
Getting Started with the MATLAB Simulation Environment
SESSION GOAL: 1. To provide a short introduction to MATLAB 2. To understand how to get started with the vector-matrix computations 3. To simulate a linear filter in the vector form

1. Introduction to MATLAB: what is MATLAB


MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation. Typical uses include: Math and computation Algorithm development Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including Graphical User Interface building MATLAB is an interactive system whose basic data element is an array that does not require dimensioning. This allows you to solve many technical computing problems, especially those with matrix and vector formulations, in a fraction of the time it would take to write a program in a scalar noninteractive language such as C or Fortran. The name MATLAB stands for matrix laboratory. MATLAB has evolved over a period of years with input from many users. In university environments, it is the standard instructional tool for introductory and advanced courses in mathematics, engineering, and science. In industry, MATLAB is the tool of choice for high-productivity research, development, and analysis. MATLAB features a family of application-specific solutions called toolboxes. Very important to most users of MATLAB, toolboxes allow you to learn and apply specialized technology. Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to solve particular classes of problems. Areas in which toolboxes are available include signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many others. The MATLAB system consists of five main parts:

Lab 1. - English

Espaol

Sesin de Laboratorio No. 1


Iniciando en el Ambiente de Simulacin de MATLAB Objetivos de la Sesin Proveer de una breve introduccin a MATLAB Entender como comenzar los clculos vectoriales-matriciales 1.Simular un filtro lineal forma vectorial Introduccin aen MATLAB. MATLAB es un lenguaje de alto desempeo para clculos tcnicos. Integra funciones de computacin, visualizacin y programacin en un ambiente de fcil manejo, donde los problemas y soluciones se expresan en la familiar notacin matemtica. Entre los usos tpicos de MATLAB estn: Matemticas y computacin Desarrollo de Algoritmos Modelado, Simulacin y Prototipos Anlisis de Datos, Exploracin y Visualizacin Grficas Cientficas o de Ingeniera Desarrollo de Aplicaciones, incluyendo la construccin de la Interface Grfica de Usuario.

MATLAB es un sistema interactivo que tiene como dato base un arreglo que no requiere ser dimensionado Esto permite resolver muchos problemas tcnicos computacionales, especficamente aquellos con planteamientos de vectores y matrices, en una fraccin de tiempo de la que tomara escribir un programa en un lenguaje escalar no interactivo como C o Fortran. El nombre MATLAB proviene de las siglas en ingles para matrix laboratory. En el ambiente universitario, es la herramienta estndar para los cursos introductorios y avanzados de matemticas, ingeniera y ciencias. En la industria MATLAB es la herramienta elegida para la investigacin, el desarrollo y el anlisis de alta productividad. MATLAB tiene una familia de soluciones para aplicaciones especficas denominadas toolboxes. Importantsimo para la mayora de los usuarios de MATLAB, los toolboxes permiten aprender y aplicar tecnologa especializada. Los toolboxes son colecciones muy completas de funciones (M-files) que aumentan el ambiente de MATLAB para la solucin de clases particulares de problemas. Algunas de las reas en las que los toolboxes estn disponibles son en procesamiento de seales, control de sistemas, redes neuronales, lgica difusa, ondeletas, simulacin, entre muchas otras.

El sistema MATLAB consiste de 5 partes principales:

Lab 1. - Espaol

English

The MATLAB language.


This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented programming features. It allows both "programming in the small" to rapidly create quick and dirty throw-away programs, and "programming in the large" to create complete large and complex application programs.

The MATLAB working environment.


This is the set of tools and facilities that you work with as the MATLAB user or programmer. It includes facilities for managing the variables in your workspace and importing and exporting data. It also includes tools for developing, managing, debugging, and profiling M-files, MATLAB's applications.

Handle Graphics.
This is the MATLAB graphics system. It includes high-level commands for twodimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level commands that allow you to fully customize the appearance of graphics as well as to build complete Graphical User Interfaces on your MATLAB applications.

The MATLAB mathematical function library.


This is a vast collection of computational algorithms ranging from elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms.

The MATLAB Application Program Interface (API).


This is a library that allows you to write C and Fortran programs that interact with MATLAB. It include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.

2. About programming in MATLAB


MATLAB is a powerful programming language as well as an interactive computational environment. Files that contain code in the MATLAB language are called M-files. You create M-files using a text editor, then use them as you would any other MATLAB function or command. There are two kinds of M-files: Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace. Functions, which can accept input arguments and return output arguments. Internal variables are local to the function. Lab 1. - English

Espaol

El lenguaje MATLAB Se trata de un lenguaje de alto nivel de matriz / array con declaraciones de flujo de control, funciones, estructuras de datos, entrada/salida, y rasgos de programa mediante objetos. Permite tanto "de programacin pequea "para crear rpidamente de forma instantnea programas desechables, y "la programacin grande "para crear programas grandes y completas aplicaciones complejas. El ambiente de trabajo de MATLAB Este es el conjunto de herramientas y facilidades que usted trabaja con MATLAB como el usuario o programador. Ello incluye facilidades para el manejo de las variables en su rea de trabajo e importacin y exportacin de datos. Tambin incluye herramientas para el desarrollo, gestin, depuracin y compilacin de M-archivos, aplicaciones de MATLAB. Los manejadores de grficos (Handle Graphics) Esto es el sistema MATLAB de grficos. Esto incluye comandos de alto nivel para la visualizacin de datos bidimensional y tridimensional, el procesamiento de imgenes, la animacin, y la grfica de presentacin. Esto tambin incluye los comandos de bajo nivel que permiten personalizar totalmente el aspecto de grfica as como construir Interfaces Graficas completas de Usuario sobre aplicaciones en MATLAB. La biblioteca de funciones matemticas de MATLAB Se trata de una vasta coleccin de algoritmos computacionales que van desde funciones elementales como suma, seno, coseno, y aritmtica compleja, a las funciones ms sofisticadas como matriz inversa, matriz de valores propios, funciones de Bessel, y transformada rpida de Fourier. EL API (Interface de Aplicacin de Programa) de MATLAB Esto es una biblioteca que le permite escribir programas en C y Fortran que actan recprocamente con MATLAB. Esto incluye la facilidad de llamar rutinas de MATLAB (la unin dinmica), llamando a MATLAB como un motor computacional, y para leer y escribir archivos .mat.

2. La programacin en MATLAB
MATLAB es poderoso lenguaje de programacin axial como un ambiente interactivo de computacin. Los archivos que contienen cdigo en el lenguaje de MATLAB son llamados archivos M o M-files. Existen 2 tipos de archivos M. Scripts, que no aceptan argumentos de entrada ni regresan argumentos de salida. Estos operan sobre los datos en el espacio de trabajo. Funciones, que aceptan argumentos de entrada y regresan argumentos de salida. Variables internas son locales para la funcin.

Lab 1. - Espaol

English

If you're a new MATLAB programmer, just create the M-files that you want to try out in the current directory. As you develop more of your own M-files, you will want to organize them into other directories and personal toolboxes that you can add to MATLAB's search path. If you duplicate function names, MATLAB executes the one that occurs first in the search path. To view the contents of an M-file, for example,
myfunction myfunction.m,

use type

Scripts When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that they create remain in the workspace, to be used in subsequent computations. In addition, scripts can produce graphical output using functions like plot.

3. Getting started: PART 1. Working with the Scripts


To run MATLAB on a PC or Mac, double-click on the MATLAB icon. If you feel you need more assistance, type help at the MATLAB prompt, or pull down on the Help menu on a PC or Mac. Working with scalars Input >> a = 2^3 (enter) a= 8 >> A = a + 10 (enter) A= 18 >> A a (enter) ans = 10 You see that MATLAB is case sensitive: it makes difference between lowercase a and uppercase A.

Lab 1. - English

Espaol Si usted es un nuevo programador MATLAB, solamente crea los Archivos .m que usted quiera probar en el directorio actual. Como usted desarrolla ms de sus propios Archivos de m, usted querr organizarlos en otros directorios y toolboxes personales que usted puede aadir al camino de bsqueda del MATLAB. Si usted duplica nombres de funcin, MATLAB ejecuta el que que ocurre primero en el camino de bsqueda. Para ver el contenido de un Archivo de m, por ejemplo, myfunction.m, el empleo escribe my function Scrips Cuando se invoca un script, MATLAB simplemente ejecuta el comando encontrado en el archivo. Los scripts pueden operar sobre datos ya existentes en el espacio de trabajo, o pueden crear nuevos datos sobre los cuales operar. A pesar de que los scripts no regresan argumentos de salida, cualquier variable que estos creen se preserva en el espacio de trabajo, para ser usado en clculos subsecuentes. Adems, los scripts pueden producir grficos de salida usando funciones como plot.

3. Por dnde empezar: PARTE 1. Trabajando con los scripts


Para ejecutar MATLAB en una PC o Mac, haga doble clic sobre el icono de MATLAB. Si siente que necesita ms asistencia, escriba help en el prompt de MATLAB. Trabajando con escalares. >> a=2^3 a= 8 >> A=a+10 A= 18 >> A-a ans = 10 % matlab es sensitivo a maysculas minsculas

Lab 1. - Espaol

English

Working with matrices Input >> a = [1 2 3] a= 123 >> b = [1;2;3] b= 1 2 3 - column vector - row vector

>> a*b ans = 14

-vector multiplication (inner product)

a + b ans = 246 >> c = [a 2*a] c= 123246

- sum of a and b transpose

- vector concatenation (joining vectors)

>> d = [a; 2*a] d= 123 246

- forms a matrix from two vectors a and 2*a

We may use concatenation for joining the string variables. Here is the example: >> a = Hello,; >> b = world!;

Lab 1. - English

Espaol >> [a b] ans = Trabajando con matrices. >> a=[1 2 3] a= 1 2 3 % vector renglon

>> b=[1;2;3] b= 1 2 3

% vector columna

>> a*b ans = 14

% producto punto

>> a+b' ans = 2 4 6

% suma de a y la transpuesta de b

>> c=[a 2*a] c= 1 2 3 2 4 6

% vector de concatenacin

>> d= [a; 2*a] d= 1 2 2 4 3 6

% formacin de una matriz de 2 vectores

>> a='Hello,'; >> b='world!' b= world!

% asignacin de una cadena a una variable

Lab 1. - Espaol

English

>> [a b] ans = Hello, world!

>> A = [1 1 2; 3 3 4; 1 2 3] - square 3-by-3 matrix A= 112 334 123 >> det(A) ans = 2 >> A * inv{A) ans = 1.0000 0 0 0 1.0000 0 0 0 1.0000 - a function that returns the determinant of a matrix

- a matrix A multiplied by the inverse matrix inv(A)

We have introduced here two simplest examples of invoking the MATLAB functions. Continue the study of the MATLAB functions invoking the MATLAB Help/ Examples and Demos/ Matrices/ Basic matrix operations.

4. Continuing the study working with the scripts


Continue studying of how to use MATLAB for vector-matrix manipulations by carrying out the following: 1. Run the given above examples on your computer. 2. Modify your examples for the vectors of dimension N (specify N as a parameter). 3. Make concatenations for the vectors of dimension N. 4. Form matrices of different dimensions using concatenations. 5. Compose a zero-vector and a unity-vector of different dimensions. Use the MATLAB functions zeros() and ones(). Display the results in the screen.

Lab 1. - English

Espaol

Hello, world! >> A = [1 1 2; 3 3 4; 1 2 3] - square 3-by-3 matrix A= 112 334 123 >> det(A) - % la funcin retorna el determinante de la matriz ans = 2 >> A * inv{A) %Multiplicacion de la matriz A por la matriz inversa A ans = 1.0000 0 0 0 1.0000 0 0 0 1.0000 Hemos introducido aqu dos ejemplos simples de invocar funciones en MATLAB. Siga el estudio de las funciones de MATLAB que invocan la Ayuda de MATLAB / Ejemplos y Demos/ matrices/ operaciones Bsicas de la matriz.

4.Continuando con el estudio trabajando con scrips.


Siga estudiando de como usar MATLAB para manipulaciones vector--matriz realizando lo siguiente:

1. Ejecute el ejemplo dado ms arriba en su computadora. 2. Modificar su ejemplo para los vectores de dimensin N (N especificar como un parmetro). 3. Haga concatenaciones de los vectores de dimensin N. 4. Forme matrices de dimensiones usando diferentes concatenaciones. 5. Componer un vector cero y un vector unidad de diferentes dimensiones. Utilice la funcin de MATLAB zeros() y ones(). Mostrar los resultados en la pantalla.

Lab 1. - Espaol

English

6. Understand how to compute the inner products, determinants of matrices and inverse matrices in MATLAB by running the examples of scripts . 7. Understand how to create graphs in MATLAB using standards commands: 7.1. Plot the result of the vector summation commands: >> plot(A) and >> grid off ; >> bar(A) , 7.3. Plot A = a + b with grid lines. Use the

7.2. Make graph type "bar" with axis labels using the commands: >> xlabel('string') >> ylabel('string'); Use the commands: and specify N . A using applying symbols in plot (for example, '*'). >> plot(A, '*') , axis(0 N 0 N)

8. Understand how to multiply the correspondent elements of two matrices using the .* operation. Run an example. 9. Understand how to obtain: 9.1. The eigenvalues of a matrix using function >> eig(A); 9.2. The characteristic polynomial of a matrix using >> p = round(poly(a)); 9.3. The roots of a polynomial using >> p = roots(p); 10. Understand how to convolve two vectors and display the result as a graph. Try two various ways: 1st using function >> conv(a,b); 2nd using element-by-element multiplication >> a.*b; Display the results using function >>plot(r); Run the example: >> r = conv(a,b); plot(r) .

11. Understand how to work with the MATLAB Help and Demo Environment running the examples from the MATLAB Demo Window.

5. Getting started: PART 2. Creating the M-Files


Introduction to MATLAB functions Functions Functions are M-files that can accept input arguments and return output arguments. The name of the M-file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt.

Lab 1. - English

Espaol

1. Entender la forma de calcular productos internos, determinantes de matrices e inversa de matrices en MATLAB ejecutando los ejemplos de scripts. 2. Entender cmo crear grficos en MATLAB utilizando los comandos standar: 7,1. Parcela el resultado de la suma vectorial A = a + b con cuadrcula. Utilice los comandos: >> Plot(A) y >> grid off; 7,2. Haga grfico tipo "bar", con las etiquetas de los ejes >> Bar (A), >> xlabel ( 'cadena') >> mediante los comandos: ylabel ( 'cadena');

7,3. Trazar una aplicacin utilizando smbolos en la parcela (por ejemplo,'*'). Utilice los comandos: >> Plot (A, '*'), eje (0 N 0 N) y especificar N. 3. Entender cmo se multiplican los elementos correspondientes de dos matrices utilizando el operador .*. Ejecutar un ejemplo. 4. Entender la forma de obtener: 9,1.Los valores propios de

una

matriz usando

la

funcin>>

eig(A);

9,2. El polinomio caracterstico de una matriz usando>> p = round (poly (a)); 9,3. Las races de un polinomio utilizando>> p = roots(p); 5. Entender la Convolucin de dos vectores y mostrar el resultado en un grfico. Trate las dos formas: 1 funcin utilizando >> conv (a, b); 2 usando multiplicacin elemento por elemento >> a. * b; Mostrar los resultados utilizando la funcin >> plot (r); Ejecute el ejemplo:>> r = conv (a, b); plot (r). 6. Entender cmo trabajar con la ayuda de MATLAB y el funcionamiento del Ambiente Demo ejecutando ejemplos Demos de la ventana de MATLAB.

5. Por dnde empezar: PARTE 2. Creacin de la M-Files


Introduccin a las funciones de MATLAB. Funciones Las funciones son M-Files que puede aceptar argumentos de entrada y regresar argumentos de salida. El nombre del M-file y de la funcin debe ser la misma. Funciones operan sobre las variables dentro de su propio espacio de trabajo, aparte de la de trabajo que el acceso a los comandos MATLAB. Lab 1. - Espaol

English

Let us start with the following example. function s = summa2(x) % SUMMA2(X) computes the sum of squared values of the numbers that compose vector X
s = 0; for i = 1:length(x) s = s + x(i)^2; end

Save this file as SUMMA2.M. The first line of a function M-file starts with the keyword function. It gives the function name and order of arguments. In this case, there are one input argument and one output argument. The next several lines, up to the first blank or executable line, are comment lines that provide the help text. These lines are printed when you type >> help summa2 The rest of the file is the executable MATLAB code defining the function. The variable s introduced in the body of the function is local to the function; it is separate from any variables in the MATLAB workspace.
>> summa2([1 2 3]) ans =

14 Vectorization To obtain the most speed out of MATLAB, it's important to vectorize the algorithms in your M-files. Where other programming languages might use For or Do loops, MATLAB can use vector or matrix operations. A vectorized version of the program code of function SUMMA2 presented above is function s=summa2(x) % SUMMA2(X) computes the sum of squared values of the numbers that compose vector X
s = 0; s = sum(x.*x);

- operator .* defines element-by-element multiplication

Lab 1. - English

Espaol

Vamos a empezar con el siguiente ejemplo. function s = summa2(x) % SUMMA2(X) computes the sum of squared values of the numbers that compose vector X s = 0; for i = 1:length(x) s = s + x(i)^2; end Guardar este archivo como SUMMA2.M. La primera lnea de una funcin m-file comienza con la palabra clave de la funcin. Esto da el nombre de la funcin y el orden de argumentos. En este caso, tenemos un argumento de entrada y un argumento de salida. Las siguientes lneas, hasta la primera lnea en blanco o ejecutable, son lneas de comentario que proporcionan el texto de ayuda. Estas lneas son imprimidas cuando usted escribe. >> help summa2 El resto del archivo es el cdigo de MATLAB ejecutable que define la funcin. La variable s es introducida en el cuerpo de la funcin y es local a la funcin; es separado de cualquier variable en el espacio de trabajo MATLAB. >> summa2([1 2 3]) ans = 14 Vectorizacion Para obtener la mayor velocidad de MATLAB, es importante que vectorize los algoritmos en su Mfiles. Donde otros lenguajes de programacin podran usar for o Do loops, MATLAB pueden usar vectores u operaciones de la matriz. Una versin vectorized del cdigo de programa de funcin SUMMA2 presentado arriba es: function s=summa2(x) % SUMMA2(X) Calcula la suma de los valores cuadrados que componen el vector s = 0; s = sum(x.*x); - operador .* define multiplicacin elemento por elemento

Lab 1. - Espaol

English

For more complicated code, vectorization options are not always so obvious. When speed is important, however, you should always look for ways to vectorize your algorithms. MATLAB provides four functions that generate basic matrices:
zeros

All zeros
ones

All ones
rand

Uniformly distributed random elements


randn

Normally distributed random elements Some examples: >>Z = zeros(2,4)


Z= 0 0 0 0 0 0 0 0

>>F = 5*ones(3,3) F= 5 5 5 5 5 5 5 5 5 >>N = fix(10*rand(1,10)) N= 4 9 4 4 8 5

Lab 1. - English

Espaol

Para obtener un codigo mas complicado, las opciones de vectorizacin no son siempre tan evidentes. Cuando la velocidad es importante, sin embargo, siempre debe buscar maneras de vectorizar sus algoritmos. MATLAB ofrece cuatro funciones bsicas que generan matrices:

zeros Todos ceros

ones Todos unos

rand Valores aleatorios uniformemente distribuidos

randn Valores aleatorios normalmente distribuidos

Algunos ejemplos: >>Z = zeros(2,4) Z= 0000 0000 >>F = 5*ones(3,3) F= 555 555 555 >>N = fix(10*rand(1,10)) N= 4944852680 Lab 1. - Espaol

English

M-Files You can create your own matrices using M-files, which are text files containing MATLAB code. Just create a file containing the same statements you would type at the MATLAB command line. Save the file under a name that ends in .m. For example, create a file containing these five lines:
A = [ ... 16.0 3.0 5.0 10.0 9.0 6.0 4.0 15.0 2.0 13.0 11.0 8.0 7.0 12.0 14.0 1.0 ];

Store the file under the name magik.m. Then the statement >>magik reads the file and creates a variable, A, containing our example matrix.

Concatenation Concatenation is the process of joining small matrices to make bigger ones. In fact, you made your first matrix by concatenating its individual elements. The pair of square brackets, [], is the concatenation operator. Deleting Rows and Columns You can delete rows and columns from a matrix using just a pair of square brackets. For any matrix A start with >>X = A; Then, to delete the second column of X, use
>>X(:,2) = []

Creating a Plot The plot function has different forms, depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x. For example, to plot the value of the sine function from zero to 2, use >> t = 0:pi/100:2*pi; >> y = sin(t);

Lab 1. - English

Espaol

M-Files Usted puede crear sus propias matrices usando M-archivos, que son archivos de texto que contienen cdigo de MATLAB. Simplemente crear un archivo que contiene las mismas declaraciones que usted escriba en la lnea de comandos MATLAB. Guarde el archivo bajo un nombre que termina en. M. Por ejemplo, cree un archivo que contenga estas cinco lneas: A = [ ... 16.0 3.0 2.0 13.0 5.0 10.0 11.0 8.0 9.0 6.0 7.0 12.0 4.0 15.0 14.0 1.0 ]; Guarde el archivo con el nombre magik.m. A continuacin la declaracin. >> Magik lee el archivo y cree una variable, A, que contiene matriz de nuestro ejemplo. Concatenacin Concatenacin es el proceso de adhesin a las pequeas matrices para hacerlas ms grandes. De hecho, usted ha hecho su primera matriz de concatenar cada uno de sus elementos. El par de corchetes, [], es el operador de concatenacin.

Eliminar filas y columnas. Puede eliminar filas y columnas de una matriz usando slo un par de corchetes. Para cualquier matriz A de comenzar con: >> X = A; Entonces, para suprimir la segunda columna de X, usar >> X (:, 2) = [] la Creacin Plot La funcin plot tiene formas diferentes, dependiendo los argumentos de entrada. Si y es un vector, el plot (y) produce un grfico piecewise lineal de los elementos de y contra el ndice de los elementos de y. Si usted especifica dos vectores como argumentos, el argumento (x, y) produce un grfico de y contra x. Por ejemplo, para trazar el valor del seno funcionan del cero a 2pi, use: >> t = 0:pi/100:2*pi; >> y = sin(t); Lab 1. - Espaol

English

plot(t,y)

- or you may use function plot(y)

Multiple x-y pairs create multiple graphs with a single call to plot. MATLAB automatically cycles through a predefined (but user settable) list of colors to allow discrimination between each set of data. For example, these statements plot three related functions of t, each curve in a separate distinguishing color: >> y2 = sin(t-.25); >> y3 = sin(t-.5); >> plot(t,y,t,y2,t,y3)

Subplots The subplot function allows you to display multiple plots in the same window or print them on the same piece of paper. Typing >> subplot(m,n,p) breaks the figure window into an m-by-n matrix of small subplots and selects the pth subplot for the current plot. The plots are numbered along first the top row of the figure window, then the second row, and so on. For example, you may modify the above program as follows, >> t = 0:pi/100:2*pi; >> y = sin(t); >> subplot(3,1,1); >> plot(y) >> y2 = sin(t-.25); >> subplot(3,1,2); >> plot(y2) >> y3 = sin(t-.5); >> subplot(3,1,3); >> plot(y3) You may use function title('string') to add title to current Axes. (For more details read the item Getting Started from MATLAB Help Desk)

6. Continuing the study working with the M-Files


Continue studying of how to use MATLAB for signal processing and simulation by carrying out the llowing: Compose the fragments of the given above examples into the compounded script for computing the matrix products and the vector signal inner product. Understand how to plot the graphs of the functions. Run the following examples: Example 1. Solid curve: >> x=0:0.05:5; y=sin(x.^2); plot(x,y);

Lab 1. - English

Espaol

>> plot(t,y)

o se puede usar la funcion plot(y)

Mltiples pares de x-y crean mltiples grficos con una llamada a plot. MATLAB automticamente crea ciclos predefinido lista de colores para permitir a discriminacin entre cada juego de datos. Por ejemplo, estas declaraciones trazan tres funciones relacionadas de t, cada curva en un color diferente:
>> y2 = sin(t-.25); >> y3 = sin(t-.5); >> plot(t,y,t,y2,t,y3)

Subplots La funcin subplot le permite mostrar mltiples argumentos en la misma ventana o imprimirlos sobre la misma hoja de papel. Mecanografa.
>> subplot(m,n,p)

Divide la ventana de figura en una matriz de m-por-n de pequeos subplot y selecciona el subplot para el argumento actual. Los argumentos son numerados a lo largo de primera fila superior de la ventana de figura despus la segunda fila, etctera. Por ejemplo, usted puede modificar el susodicho programa as, >> t = 0:pi/100:2*pi; >> y = sin(t); >> subplot(3,1,1); >> plot(y) >> y2 = sin(t-.25); >> subplot(3,1,2); >> plot(y2) >> y3 = sin(t-.5); >> subplot(3,1,3); >> plot(y3) Puede usar la funcin title ( 'string') y agregar ttulos a los ejes actuales. (para mas detalles leer la ayuda que ofrece Matlab)

6. Continuacin del estudio que trabaja con los m-Archivos.


Continuar estudiando cmo usar MATLAB para el tratamiento de seal y la simulacin realizando el llowing: 1. calcular los productos de la matriz y el producto interno del vector seal. 2. Entender como trazar los grficos de las funciones. ejecutar los ejemplos siguientes: Ejemplo 1. Curva slida:>> x=0:0.05:5; y=sin (x. ^ 2); plot (x, y);

Lab 1. - Espaol

English

Example 2. Bar plot of a bell shaped curve: >> x=-2.9:0.1:2.9; bar(x, exp(-x.*x)) Example 3. Stem plot: >> x=0:0.1:4; y=sin(x.^2).*exp(-x); stem(x,y)

Example 4. Error bar: >> x=-2:0.1:2; y=erf(x); e=rand(size(x))/10; errorbar(x,y,e) 3. Understand how to create a toeplitz-form matrix using function toeplitz(a); 4. Understand how to display the 3-D graph of a matrix using function mesh(A); surf(A); countor(A) . Example 1. Example 2. Example 3. A=peaks(25);mesh(A) A=peaks(25);surf(A) A=peaks(25);contour(A)

5. Understand how to display the results of vector-matrix computations using mesh(), subplot(), plot(), xlabel() ylabel() and title() functions. 6. Create your own examples of M-file to run the programs of the above tasks.

________________________________________________

7. Practical Example: Simulating a Linear Filter in the Vector Form


SESSION GOAL: Consider given: 1. N - the dimension (length) of the information signal vector v ; 2. Ampl the maximum value of the information vector magnitude; 3. N0 constant white noise density (noise variance); 4. K - the width of the system spread function (system instrumental matrix) S ; Perform the following computations and simulations: 1. Compute and graph the information vector v for a given set of the nonzero elements and the white Gaussian noise vector n; 2. Compute and graph the system matrix S of a toeplitz form for the given (computed) first row of the matrix S; 3. Compute and graph the resultant degraded (smoothed and noised) data vector u = Sv + n .

Lab 1. - English

Espaol

Ejemplo 2. Bar plot de una curva de campana: >> x =-2.9:0.1:2.9; barra (x, exp (-x.*x)) Ejemplo 3. Stem plot: >> x=0:0.1:4; y=sin(x.^2).*exp(-x); stem(x,y) Ejemplo4. Error bar: >> x=-2:0.1:2; y=erf(x); e=rand(size(x))/10; errorbar(x,y,e) 3 Entender cmo crear una forma de toeplitz matriz usando la funcin toeplitz (a); 4. Entender cmo mostrar el 3-D grfico de una matriz usando la funcin de mesh (A); surf (A); countor (A). Ejemplo 1. A=peaks(25);mesh(A) Ejemplo2. A=peaks(25);surf(A) Ejemplo 3. A=peaks(25);contour(A) 1. Entender como mostrar los resultados de calculos vector-matriz usando las funciones mesh (), subplot(), plot(), xlabel () ylabel () y title(). 2. Crear sus propios ejemplos M-File para ejecutar los programas de las tareas comentadas.

7. Ejemplo Prctico: Simulando un Filtro lineal en Forma Vectorial Objetivo de la sesin. Considere dadas: 1.-N La dimensin (longitud) de la seal de informacin vectorial v; 2.-Ampl. El valor mximo de la magnitud del vector informacin; 3.-N0 Constante de densidad de ruido blanco (varianza del ruido); 4.-K El ancho de la funcin de dispersin del sistema (matriz instrumental del sistema) S; Realice los siguientes clculos y simulaciones: 1.-Calcule y grafique el vector v para un conjunto dado de elementos no nulos y el vector de ruido blanco Gaussiano n; 2.-Calcule y grafique la matriz del sistema S de forma toeplitz para un primer rengln dado (calculado). 3.-Calcule y grafique el vector de datos degradado resultante (suavizada y con ruido) u = Sv + n.

Lab 1. - Espaol

English

7.1. Formation of the information signal vector Initialize the information vector as v=zeros(N,1); Assign the nonzero elements of the information vector as follows: v(30,1)=0.6*Ampl; v(45,1)=0.1*Ampl; v(90,1)=0.4*Ampl; This fragment of the program returns the information vector that has three nonzero elements in positions 30, 45 and 90 with amplitudes that are the fractions of the parameter Ampl. 7.2. Formation of the system matrix. To form the system matrix S it is convenient to use the special so-called toeplitz function as S=toeplitz(b); where b denotes the vector of the first column (or the first row) of a toeplitz matrix. Example Consider the rectangular shape of the system response function rect(K) of a given width K . Then we may program the procedure for forming the relevant system matrix S as follows: b=zeros(N,1); for i=1:floor(K/2), b(i)=a; end S=toeplitz(b); Perform the following computations: Modify the written above program for forming the system matrices that simulate the two other system spread (instrumental) function models: ) S2(x) = rect(K) exp(x2/a) b) S3(x) = rect(K)| sin(ax)/ax | Consider the given width K for the both functions.

Hint: The following fragments of the programs may be used:


) b=zeros(N,1); for i=1:2*floor(K/2), b(i+1)=exp(i*i/a); end b(1)=1;

Lab 1. - English

Espaol

7.1.- Formacin del vector de informacin


Inicialice el vector informacin como v=zeros(N,1); Asigne los elementos no nulos del vector informacin como sigue: v(30, 1)=0.6*Ampl; v(45, 1)=0.6*Ampl; v(60, 1)=0.6*Ampl; Esta parte de programa devuelve el vector informacin que contiene tres elementos no nulo en la posicin 30, 45 y 90 con amplitudes que son fracciones del parmetro Ampl.

7.2 Formacin de la matriz del Sistema


Para formar la matriz del sistema S es conveniente usar la funcin llamada toeplitz como en: S=toeplitz(b); Donde b denota el vector de la primera columna (o el primer rengln) de una matriz toeplitz. 1. Ejemplo Considerar la forma rectangular de la respuesta del sistema de funcin rect (K) de un determinado ancho K. Entonces podemos programar el procedimiento para la formacin de los sistema como matriz S la siguiente manera: b=zeros(N,1); for i=1:floor(K/2), b(i)=a; end S=toeplitz(b); 2. Realice los siguientes clculos: Modificar el programa anterior por escrito para que formen el sistema de matrices que simulan los otros 2 sistemas de difusin los modelos de funcin: S2(x) = rect(K) exp(x2/a) b) S3(x) = rect(K)| sin(ax)/ax | Considere la posibilidad de dar el ancho K para ambas funciones. Idea: Los siguientes fragmentos de los programas se puede utilizar: a) b=zeros(N,1); for i=1:2*floor(K/2), b(i+1)=exp(i*i/a); end b(1)=1;

Lab 1. - Espaol

English

S=toeplitz(b); b) b=zeros(N,1); for i=1:floor(K/2), b(i+1)=abs(sin(a*i/floor(K/2))/(a*i/floor(K/2))); end b(1)=1; S=toeplitz(b);

7.3. Formation of the additive Gaussian noise vector


To simulate the Gaussian noise vector the function randn(N,1) should be used (See the MATLAB HELP options for details). To obtain the resultant noise vector with the prescribed variance N0 we have to multiply the standard noise vector returned by the program randn(N,1) by the sqrt(N0). The fragment of the program is Noise=randn(N,1)*sqrt(N0);

7.4. Simulation of the resultant discrete-form equation of observation


The equation of observation in a discrete vector form is given as u = Sv + n. The fragment of the MATLAB program that returns this observation vector is u = S*v + Noise; where the signal vector v , the noise vector computed above. Noise and the system matrix S were

7.5. Composing the simulation experiment


Continue this experiment by carrying out the following:
1. Compose the fragments of the given above examples into the compounded program

for signal, noise, system and data simulation. Use three types of system matrices of a toeplitz form: S1(x) = rect(K) S2(x) = rect(K) exp(x2/a) S3(x) = rect(K) | sin(ax)/ax | 2. Graph (display) the results of simulations of v, n, S and u (for different models of ther input vector, noise intensity N0 and system matrix) using the MATLAB functions mesh(), subplot(), plot(), title(), etc . Lab 1. - English

Espaol S=toeplitz(b); b) b=zeros(N,1); for i=1:floor(K/2), b(i+1)=abs(sin(a*i/floor(K/2))/(a*i/floor(K/2))); end b(1)=1; S=toeplitz(b);

7.3. Formacin del vector aditivo de ruido Gaussiano


Para simular el vector de ruido Gaussiano la funcin randn (N, 1) debe ser utilizado (Vase la opcin de AYUDA de MATLAB para ms detalles). Para obtener el vector resultante del ruido con el prescrito N0 en la varianza tenemos que multiplicar el nivel del vector de ruido devuelto por el programa randn (N, 1) de la sqrt (N0). El fragmento del programa es n=randn(N,1)*sqrt(N0);

7.4.-Simulacin de la ecuacin de observacin resultante en forma discreta.


La ecuacin de observacin en la forma vectorial discreta esta dada por: u = Sv + n. Para simular y obtener en MATLAB el vector de salida u se utilizo la siguiente lnea de cdigo. u=S*v + Noise Donde el vector seal v, el vector de ruido Noise, y la matriz del sistema S fueron calculados anteriormente.

7.5.- Continu este experimento llevando a cabo lo siguiente:


1. Mezcle los fragmentos de los ejemplos anteriores en un programa compuesto para simulacin de seal, ruido, sistema y datos. Use tres tipos de matrices toeplitz:

S1(x)= rect(K) S2(x)= rect(K)*exp(-x2/a) S3(x)= rect(K)*|sin(ax)/ax| 2. Grafique (muestre) los resultados de la simulacin de v, n, S y u (para diferentes modelos de vector de entrada, intensidad de ruido N0 y matrices de sistema) usando las funciones de MATLAB mesh(), subplot(), plot(), title(), etc.

Lab 1. - Espaol

You might also like