Date post: | 27-Nov-2015 |
Category: |
Documents |
Upload: | ricardo-palafox |
View: | 5 times |
Download: | 0 times |
Laboratory Session # 1.
Getting Started with the MATLAB Simulation
Environment
Sesión de Laboratorio No. 1
Iniciando en el Ambiente de Simulación de
MATLAB
Lab 1. - English
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. - Español
Español
Sesión de Laboratorio No. 1
Iniciando en el Ambiente de Simulación de MATLAB
1. Introducción a MATLAB.
MATLAB es un lenguaje de alto desempeño para cálculos técnicos. Integra
funciones de computación, visualización y programación en un ambiente de fácil
manejo, donde los problemas y soluciones se expresan en la familiar notación
matemática. Entre los usos típicos de MATLAB están:
• Matemáticas y computación
• Desarrollo de Algoritmos
• Modelado, Simulación y Prototipos
• Análisis de Datos, Exploración y Visualización
• Gráficas Científicas o de Ingeniería
• Desarrollo de Aplicaciones, incluyendo la construcción de la Interface Gráfica de
Usuario.
MATLAB es un sistema interactivo que tiene como dato base un arreglo que no
requiere ser dimensionado Esto permite resolver muchos problemas técnicos
computacionales, específicamente aquellos con planteamientos de vectores y matrices,
en una fracción de tiempo de la que tomaría 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 estándar para los cursos introductorios y
avanzados de matemáticas, ingeniería y ciencias. En la industria MATLAB es la
herramienta elegida para la investigación, el desarrollo y el análisis de alta productividad.
MATLAB tiene una familia de soluciones para aplicaciones específicas
denominadas toolboxes. Importantísimo para la mayoría de los usuarios de MATLAB,
los toolboxes permiten aprender y aplicar tecnología especializada. Los toolboxes son
colecciones muy completas de funciones (M-files) que aumentan el ambiente de
MATLAB para la solución de clases particulares de problemas. Algunas de las áreas
en las que los toolboxes están disponibles son en procesamiento de señales, control de
sistemas, redes neuronales, lógica difusa, ondeletas, simulación, entre muchas otras.
El sistema MATLAB consiste de 5 partes principales:
Objetivos de la Sesión
• Proveer de una breve introducción a MATLAB
• Entender como comenzar los cálculos vectoriales-matriciales
• Simular un filtro lineal en forma vectorial
Lab 1. - English
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 two-
dimensional 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. - Español
Español
• 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 programación pequeña "para crear rápidamente de forma instantánea
programas desechables, y "la programación 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 importación y exportación de
datos. También incluye herramientas para el desarrollo, gestión, depuración y compilación
de M-archivos, aplicaciones de MATLAB.
• Los manejadores de gráficos (Handle Graphics)
Esto es el sistema MATLAB de gráficos. Esto incluye comandos de alto nivel para la
visualización de datos bidimensional y tridimensional, el procesamiento de imágenes, la
animación, y la gráfica de presentación. Esto también incluye los comandos de bajo nivel
que permiten personalizar totalmente el aspecto de gráfica así como construir Interfaces
Graficas completas de Usuario sobre aplicaciones en MATLAB.
• La biblioteca de funciones matemáticas de MATLAB
Se trata de una vasta colección de algoritmos computacionales que van desde funciones
elementales como suma, seno, coseno, y aritmética compleja, a las funciones más
sofisticadas como matriz inversa, matriz de valores propios, funciones de Bessel, y
transformada rápida de Fourier.
• EL API (Interface de Aplicación de Programa) de MATLAB
Esto es una biblioteca que le permite escribir programas en C y Fortran que actúan
recíprocamente con MATLAB. Esto incluye la facilidad de llamar rutinas de MATLAB (la
unión dinámica), llamando a MATLAB como un motor computacional, y para leer y
escribir archivos .mat.
2. La programación en MATLAB
MATLAB es poderoso lenguaje de programación axial como un ambiente interactivo de
computación. Los archivos que contienen código 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 función.
Lab 1. - English
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.m, use type myfunction
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. - Español
Español
Si usted es un nuevo programador MATLAB, solamente crea los Archivos .m que usted
quiera probar en el directorio actual. Como usted desarrolla más de sus propios Archivos de
m, usted querrá organizarlos en otros directorios y toolboxes personales que usted puede
añadir al camino de búsqueda del MATLAB.
Si usted duplica nombres de función, MATLAB ejecuta el que que ocurre primero en el
camino de búsqueda.
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 cálculos subsecuentes. Además, los scripts pueden producir
gráficos de salida usando funciones como plot.
3. Por dónde 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 más 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 mayúsculas minúsculas
Lab 1. - English
English
Working with matrices
Input
>> a = [1 2 3] - row vector
a =
1 2 3
>> b = [1;2;3] - column vector
b =
1
2
3
>> a*b -vector multiplication (inner product)
ans =
14
a + b’ - sum of a and b transpose
ans =
2 4 6
>> c = [a 2*a] - vector concatenation (joining vectors)
c =
1 2 3 2 4 6
>> d = [a; 2*a] - forms a matrix from two vectors a and 2*a
d =
1 2 3
2 4 6
We may use concatenation for joining the string variables. Here is the example:
>> a = ‘Hello,’;
>> b = ‘world!’;
Lab 1. - Español
Español
>> [a b]
ans =
Trabajando con matrices.
>> a=[1 2 3] % vector renglon
a =
1 2 3
>> b=[1;2;3] % vector columna
b =
1
2
3
>> a*b % producto punto
ans =
14
>> a+b' % suma de a y la transpuesta de b
ans =
2 4 6
>> c=[a 2*a] % vector de concatenación
c =
1 2 3 2 4 6
>> d= [a; 2*a] % formación de una matriz de 2 vectores
d =
1 2 3
2 4 6
>> a='Hello,'; % asignación de una cadena a una variable
>> b='world!'
b =
world!
Lab 1. - English
English
>> [a b]
ans =
Hello, world!
>> A = [1 1 2; 3 3 4; 1 2 3] - square 3-by-3 matrix
A =
1 1 2
3 3 4
1 2 3
>> det(A) - a function that returns the determinant of a matrix
ans =
2
>> A * inv{A) - a matrix A multiplied by the inverse matrix inv(A)
ans =
1.0000 0 0
0 1.0000 0
0 0 1.0000
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. - Español
Español
Hello, world!
>> A = [1 1 2; 3 3 4; 1 2 3] - square 3-by-3 matrix
A =
1 1 2
3 3 4
1 2 3
>> det(A) - % la función 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 Básicas 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 más arriba en su computadora.
2. Modificar su ejemplo para los vectores de dimensión N (N especificar como un
parámetro).
3. Haga concatenaciones de los vectores de dimensión N.
4. Forme matrices de dimensiones usando diferentes concatenaciones.
5. Componer un vector cero y un vector unidad de diferentes dimensiones. Utilice la
función de MATLAB zeros() y ones(). Mostrar los resultados en la pantalla.
Lab 1. - English
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 A = a + b with grid lines. Use the
commands:
>> plot(A) and >> grid off ;
7.2. Make graph type "bar" with axis labels using the commands:
>> bar(A) , >> xlabel('string') >> ylabel('string');
7.3. Plot A using applying symbols in plot (for example, '*'). Use the commands:
>> plot(A, '*') , axis(0 N 0 N) and specify 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); 2
nd 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. - Español
Español
1. Entender la forma de calcular productos internos, determinantes de matrices e
inversa de matrices en MATLAB ejecutando los ejemplos de scripts.
2. Entender cómo crear gráficos en MATLAB utilizando los comandos standar:
7,1. Parcela el resultado de la suma vectorial A = a + b con
cuadrícula. Utilice los comandos:
>> Plot(A) y >> grid off;
7,2. Haga gráfico tipo "bar", con las etiquetas de los ejes mediante los comandos:
>> Bar (A), >> xlabel ( 'cadena') >> ylabel ( 'cadena');
7,3. Trazar una aplicación utilizando símbolos en la parcela (por ejemplo,'*').
Utilice los comandos:
>> Plot (A, '*'), eje (0 N 0 N) y especificar N.
3. Entender cómo 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 función>> eig(A);
9,2. El polinomio característico de una matriz usando>> p = round (poly (a));
9,3. Las raíces de un polinomio utilizando>> p = roots(p);
5. Entender la Convolución de dos vectores y mostrar el resultado en un gráfico. Trate
las dos formas: 1 ª función utilizando >> conv (a, b); 2 ª usando multiplicación
elemento por elemento >> a. * b; Mostrar los resultados utilizando la función
>> plot (r);
Ejecute el ejemplo:>> r = conv (a, b); plot (r).
6. Entender cómo trabajar con la ayuda de MATLAB y el funcionamiento del
Ambiente Demo ejecutando ejemplos Demos de la ventana de MATLAB.
5. Por dónde empezar: PARTE 2. Creación de la M-Files
Introducción 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 función 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. - English
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. - Español
Español
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 línea de una función m-file comienza con la palabra clave de la función. Esto da
el nombre de la función y el orden de argumentos. En este caso, tenemos un argumento de
entrada y un argumento de salida.
Las siguientes líneas, hasta la primera línea en blanco o ejecutable, son líneas de
comentario que proporcionan el texto de ayuda. Estas líneas son imprimidas cuando usted
escribe.
>> help summa2
El resto del archivo es el código de MATLAB ejecutable que define la función. La variable
s es introducida en el cuerpo de la función y es local a la función; 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 programación podrían usar for o Do loops,
MATLAB pueden usar vectores u operaciones de la matriz. Una versión vectorized del
código de programa de función 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 multiplicación elemento por elemento
Lab 1. - English
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 2 6 8 0
Lab 1. - Español
Español
Para obtener un codigo mas complicado, las opciones de vectorización no son siempre tan
evidentes. Cuando la velocidad es importante, sin embargo, siempre debe buscar maneras
de vectorizar sus algoritmos.
MATLAB ofrece cuatro funciones básicas 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 =
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 2 6 8 0
Lab 1. - English
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 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 ];
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. - Español
Español
M-Files
Usted puede crear sus propias matrices usando M-archivos, que son archivos de texto que
contienen código de MATLAB. Simplemente crear un archivo que contiene las mismas
declaraciones que usted escriba en la línea de comandos MATLAB. Guarde el archivo bajo
un nombre que termina en. M. Por ejemplo, cree un archivo que contenga estas cinco
líneas:
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 continuación la declaración.
>> Magik
lee el archivo y cree una variable, A, que contiene matriz de nuestro ejemplo.
Concatenación
Concatenación es el proceso de adhesión a las pequeñas matrices para hacerlas más
grandes. De hecho, usted ha hecho su primera matriz de concatenar cada uno de sus
elementos. El par de corchetes, [], es el operador de concatenación.
Eliminar filas y columnas.
Puede eliminar filas y columnas de una matriz usando sólo 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 Creación Plot
La función plot tiene formas diferentes, dependiendo los argumentos de entrada. Si y es un
vector, el plot (y) produce un gráfico 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 gráfico 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. - English
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. - Español
Español
>> plot(t,y) – o se puede usar la funcion plot(y)
Múltiples pares de x-y crean múltiples gráficos con una llamada a plot. MATLAB
automáticamente crea ciclos predefinido lista de colores para permitir a discriminación
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 función subplot le permite mostrar múltiples argumentos en la misma ventana o
imprimirlos sobre la misma hoja de papel. Mecanografía. >> subplot(m,n,p)
Divide la ventana de figura en una matriz de m-por-n de pequeños 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 después la segunda fila, etcétera. 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 función title ( 'string') y agregar títulos a los ejes actuales. (para mas detalles
leer la ayuda que ofrece Matlab)
6. Continuación del estudio que trabaja con los m-Archivos.
Continuar estudiando cómo usar MATLAB para el tratamiento de señal y la simulación
realizando el llowing:
1. calcular los productos de la matriz y el producto interno del vector señal.
2. Entender como trazar los gráficos de las funciones. ejecutar los ejemplos
siguientes:
Ejemplo 1. Curva sólida:>> x=0:0.05:5; y=sin (x. ^ 2); plot (x, y);
Lab 1. - English
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. A=peaks(25);mesh(A)
Example 2. A=peaks(25);surf(A)
Example 3. 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. - Español
Español
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 cómo crear una forma de toeplitz matriz usando la función toeplitz (a);
4. Entender cómo mostrar el 3-D gráfico de una matriz usando la función 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 Práctico: Simulando un Filtro lineal en Forma Vectorial
Objetivo de la sesión.
Considere dadas:
1.-N – La dimensión (longitud) de la señal de información vectorial v;
2.-Ampl. – El valor máximo de la magnitud del vector información;
3.-N0 – Constante de densidad de ruido blanco (varianza del ruido);
4.-K – El ancho de la función de dispersión del sistema (matriz instrumental del sistema) S;
Realice los siguientes cálculos 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 renglón dado
(calculado).
3.-Calcule y grafique el vector de datos degradado resultante (suavizada y con ruido)
u = Sv + n.
Lab 1. - English
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. - Español
Español
7.1.- Formación del vector de información Inicialice el vector información como
v=zeros(N,1);
Asigne los elementos no nulos del vector información 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 información que contiene tres elementos no nulo
en la posición 30, 45 y 90 con amplitudes que son fracciones del parámetro Ampl.
7.2 Formación de la matriz del Sistema Para formar la matriz del sistema S es conveniente usar la función llamada toeplitz como
en:
S=toeplitz(b);
Donde b denota el vector de la primera columna (o el primer renglón) de una matriz
toeplitz.
1. Ejemplo
Considerar la forma rectangular de la respuesta del sistema de función rect (K) de un
determinado ancho K. Entonces podemos programar el procedimiento para la formación 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 cálculos:
Modificar el programa anterior por escrito para que formen el sistema de matrices que
simulan los otros 2 sistemas de difusión los modelos de función:
� 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. - English
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 Noise and the system matrix S were
computed above.
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. - Español
Español
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. Formación del vector aditivo de ruido Gaussiano
Para simular el vector de ruido Gaussiano la función randn (N, 1) debe ser utilizado (Véase
la opción de AYUDA de MATLAB para más 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.-Simulación de la ecuación de observación resultante en forma
discreta.
La ecuación de observación 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 línea de
código.
u=S*v + Noise
Donde el vector señal 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
simulación de señal, 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 simulación 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.