viernes, 2 de junio de 2017

Libro con practicas y codigos Tratamiento de señales digitales mediante wavelets

Libro con practicas y codigos Tratamiento de señales digitales mediante wavelets
http://personales.upv.es/aperis/wavelets/senyales/indice.htm

Tratamiento
de señales
digitales
mediante
wavelets

Presentación
Programa
Descripción
Matrícula
Materiales
Enlaces
Otros

Presentación

Las wavelets y el análisis de multiresolución constituyen una potente herramienta para afrontar problemas fundamentales en el tratamiento de señales. Entre ellos se encuentran la reducción del ruido, la compresión de señales (de vital importancia tanto en la transmisión de grandes cantidades de datos como en su almacenamiento) o la detección de determinados patrones o irregularidades locales en ciertos tipos de señales (electrocardiogramas, vibraciones de motores, etc.).  Esta moderna teoría ha experimentado un gran desarrollo en las dos últimas décadas mostrándose muy eficiente donde otras técnicas, como por ejemplo la transformada rápida de Fourier, no resultaban satisfactorias.  Este curso pretende ser una introducción al tratamiento de señales mediante wavelets. Los prerrequisitos necesarios son poco exigentes y se reducen a conocimientos básicos de álgebra lineal. Puesto que el objetivo es claramente práctico, las clases se desarrollarán en aulas informáticas desde el inicio utilizando software específico (Wavelet Toolbox de MatLab).
Algunos de los principales problemas que afectan al tratamiento de señales digitales son la compresión de datos para su posterior almacenamiento o transmisión, la eliminación del ruido,  y detección de ciertos fenómenos locales.
Las wavelets proporcionan un conjunto de herramientas flexible para problemas prácticos en ciencia e ingeniería. En la última década se han  aplicado ya con éxito al análisis de señales en distintas disciplinas tan diversas como la medicina, la ingeniería eléctrica, teledetección y muchas otras. Una de las principales virtudes de las wavelets es que permiten modelar mejor procesos que dependen fuertemente del tiempo (anisótropos) y para los cuales su comportamiento no tiene porqué ser suave.
La transformada wavelet es una transformación de la señal que la divide en dos tipos de subseñales, la tendencia y las fluctuaciones. La tendencia viene a ser una copia de la señal a menor resolución y las fluctuaciones almacenan información referida a los cambios locales en la señal inicial. La tendencia y las fluctuaciones más significativas permiten una compresión de la señal a cambio de descartar información irrelevante y de la eliminación del ruido producido por los aparatos y las condiciones de medida.  Según el tipo de medición realizada el ruido correspondiente se comporta matemáticamente siguiendo distribuciones de probabilidad gaussianas, uniformes... El estudio de las fluctuaciones permite detectar anomalías o disfunciones en el comportamiento esperado de la señal inicial. También permite la comparación con patrones para detectar formas en una señal eléctrica de forma automática. 
No existe una transformada wavelet única, ni que resuelva todos los problemas, a partir de la modelación del proceso y de un análisis a priori del tipo de señal tratada y del objetivo que se pretenda (compresión, eliminación del ruido, ...) se busca la familia de wavelets  (Haar, Daubechies, Coiflets,...) que mejor coincida con las características de la señal a estudiar. 
Una de las principales ventajas de las wavelets frente a los métodos clásicos, como la transformada de Fourier, es que en el segundo caso se maneja una base de funciones bien localizada en frecuencia pero no en tiempo, mientras que la mayoría de las wavelets interesantes presentan una buena localización en tiempo y en frecuencia, disponiendo incluso de bases de wavelets con soporte compacto. La transformada wavelet está asociada con el análisis multiresolución de la señal. A distintos niveles de resolución tenemos una base de wavelets. Concretamente, cuando mayor detalle pretendamos obtener en una señal (mayor resolución), mayor número de funciones por unidad de longitud tendremos en nuestra base de wavelets. 
Existen dos tipos de wavelets las continuas y las discretas. El tratamiento con wavelets discretas permite su aplicación directa a procesos computacionales. Las wavelets continuas presentan por una parte la dificultad de su manejo al tener que evaluar un gran número de integrales y tener en consecuencia una redundancia de información, pero por otra parte permiten la flexibilidad de poder adaptarse a situaciones en las que las discretas no dan un resultado satisfactorio.
Aplicaciones:
Ingeniería automovilística
Cartografía
Programa

  1. Introducción a la compresión y tratamiento de señales mediante la transformada wavelet. Wavelets de Haar. Introducción al software Wavelet Toolbox para señales unidimensionales de MATLAB. (14 h.) 
  2. Wavelets ortogonales. Las wavelets de Daubechies. Análisis de multiresolución. Compresión y tratamiento de señales de una variable (señales de audio). Reducción de ruido. (16 h.) 
Materiales

En esta página encontrarás todos aquellos materiales (documentos, ficheros, imágenes, etc.) necesarios para realizar las prácticas del curso.
Día 1
sig1.txt
sig.mat
Día 2
energy.m
cumenergy.m
rms.m
Señales de audio
(formato *.wav)
call_back.wav
fake_crow.wav
fake_turkey.wav
greasy.wav
the_microsoft_sound.wav
Día 4
wave_scal.m
comp_audio.m
white_noise.m
make_noisy_signal.m
denoise.m
denoise_auto.m
Día 5
corrsig.m
f.mat
g.mat
ecg.mat
arritmia.mat
ecg_big.mat
arritmia_big.mat
ecg_big_big.mat
arritmia_big_big.mat
Día 6
 

Enlaces

En esta página puedes encontrar una serie de enlaces interesantes relacionados con el curso.
Survey papers sobre wavelets:
          A. Bultheel, Learning to swim in a sea of wavelets, Bull. Belg. Math. Soc.2 (1995), no. 1, 1-46.
Sitios web de wavelets:
          Wavelet.org





Analisis Numerico Computación Numerica Metodos Numericos

Analisis Numerico Computación Numerica Metodos Numericos
Buenos Algoritmos

http://users.dsic.upv.es/asignaturas/eui/cnu/libro/

Libro Electrónico
LIBRO ELECTRÓNICO



TEMA 2  TEMA 3 TEMA 4 TEMA 5 TEMA 6 TEMA 7 TEMA 8


Tema 2

Raíces de funciones.
2.1. Métodos abiertos y cerrados. Condiciones de convergencia.
2.2. Métodos cerrados.
2.3. Métodos abiertos.
2.4. Técnica del punto fijo.
2.5. Teorema del punto fijo.
2.6. Métodos de aceleración del punto fijo.
2.7. Interpretación gráfica de la aceleración del punto fijo.
2.8. Proceso de Aitken.
2.9. Método de Steffensen.
2.10. Comparación de métodos.
2.11. Objetivos para la evaluación.
2.12. Ejercicios.
2.13. Autocontrol.


Prácticas

PRÁCTICAS

PRACTICA 1

PRACTICA 2 PRACTICA 3 PRACTICA 4 PRACTICA 5


Introducción al MATLAB.
1.1 Introducción.
1.2 Ejercicios.
1.3 Material adicional para la práctica.

PRACTICA 1.-
Introducción al MATLAB.

Objetivos para la evaluación.
 
  1. Conocer los comandos del entorno Matlab.
  2. Conocer las sentencias de repetición y decisión del lenguaje de programación Matlab.
  3. Conocer el formato de las rutinas escritas en Matlab.
  4. Escribir rutinas en lenguaje Matlab mediante ficheros .m.
  5. Utilizar los comandos de dibujo de Matlab.
  6. Utilizar la función feval de Matlab.




Tema 2
TEMA 2


TEMA 2

Raices de funciones.
Desde hace años se utiliza la fórmula cuadrática
         (2.1)
para resolver ecuaciones del tipo
.          (2.2)
A los valores calculados con la ecuación (2.1) se les llama "raíces" de la ecuación (2.2). Estas raíces representan los valores de x que anulan la ecuación (2.2). Por lo tanto, se puede definir la raíz de una ecuación como el valor de x que hace que f(x) = 0. Por esta razón, algunas veces a las raíces de una función se les conoce como ceros de la función.
Aunque la fórmula cuadrática es útil parar resolver la ecuación (2.2), hay muchas funciones que no se pueden resolver de manera tan fácil. Afortunadamente, los métodos numéricos que describiremos proporcionan medios eficientes para obtener raíces de todo tipo de ecuaciones.
Antes de la aparición de los ordenadores digitales, ya existía una serie de métodos para hallar raíces de ecuaciones algebraicas o trascendentes. En algunos casos, las raíces se podían obtener con métodos directos, como se hace con la ecuación (2.1), pero en muchos otros casos esto no era posible. Por ejemplo, hasta una función aparentemente tan simple como
no se puede resolver analíticamente. En estos casos, la única alternativa es una técnica de solución aproximada.
Una técnica para obtener una solución aproximada consiste en dibujar la función y determinar dónde corta su gráfica al eje de abscisas. Este punto, que representa el valor de x para el cual f(x) = 0, es una de las raíces de dicha ecuación.
Aunque los métodos gráficos son útiles en la obtención de estimaciones aproximadas de las raíces, están limitados por la carencia de precisión. Una aproximación alternativa consiste en usar la técnica de ensayo y error. Esta "técnica" consiste en escoger un valor de x, y evaluar si f(x) es cero. Si no es así, como sucederá en la mayoría de las ocasiones, se hace otra conjetura y se evalúa nuevamente f(x) para determinar si el nuevo valor ofrece una mejor estimación de la raíz. El proceso se repite hasta que se obtenga un valor que genere un valor de f(x) lo suficientemente cercano a cero.
Estos métodos fortuitos, obviamente son ineficientes e inadecuados para las exigencias actuales de cualquier disciplina científica. Por suerte existen técnicas que además de aproximar el valor de la raíz, emplean estrategias sistemáticas para encaminarse a ella, y son de fácil implementación en programas de ordenador. La combinación de estos métodos sistemáticos con el ordenador hace de la solución de la mayor parte de los problemas de raíces de ecuaciones una tarea que puede resolverse de forma simple y eficiente.
Aunque las raíces de ecuaciones caben dentro de otro contexto, frecuentemente aparecen en problemas de ingeniería, por ejemplo en problemas de balance de energía, balance de calor, problemas en los que aparecen las leyes de Newton del movimiento o las leyes de Kirchhoff, etc.
Un ejemplo de tales modelos se presenta en la ecuación derivada de la segunda ley de Newton, usada en el tema 1 para el cálculo de la velocidad en el ejemplo del paracaidista:
         (2.3)
Donde la velocidad v es la variable dependiente, el tiempo t es la variable independiente y g la constante gravitacional; el coeficiente de rozamiento c y la masa m son parámetros. Si se conocen los parámetros, la ecuación (2.3) se puede usar para predecir la velocidad del paracaidista como una función del tiempo. Estos cálculos se pueden llevar a cabo directamente ya que v se expresa explícitamente como una función del tiempo. Sin embargo, supóngase que se tiene que determinar el coeficiente de rozamiento para un paracaidista de una masa dada en caída libre, de modo que alcance una velocidad determinada en un periodo dado de tiempo.
Aunque la ecuación (2.3) proporciona una representación matemática de la interrelación entre las variables del modelo y los parámetros, no se puede resolver explícitamente para el coeficiente de rozamiento, es decir, no hay forma de reordenar la ecuación para despejar c a un lado de la igualdad. En estos casos se dice que c es implícita.
Esto representa un verdadero inconveniente, ya que muchos de los problemas científicos involucran la especificación de las propiedades o la composición de un sistema (representado por sus parámetros) para asegurar que funciona de la manera deseada (representada por sus variables). Por lo tanto, estos problemas a menudo requieren que se determinen sus parámetros de forma explícita.
La solución a este dilema la proporcionan los métodos numéricos para raíces de ecuaciones. Para resolver el problema usando métodos numéricos es conveniente reestructurar la ecuación (2.3). Esto se hace restando la variable dependiente v de ambos lados de la ecuación, obteniendo:
         (2.4)
Por lo tanto el valor de c que cumple f(c) = 0, es la raíz de la ecuación. Este valor también representa el coeficiente de rozamiento que soluciona el problema que nos hemos planteado.
Existen muchos métodos numéricos que permiten resolver ecuaciones tales como (2.4). A modo de ejemplo, podríamos resolver esta ecuación utilizando el llamado método del punto fijo, y ver si para los valores de masa, velocidad y tiempo obtenidos en el ejemplo del tema 1, el coeficiente de rozamiento obtenido es el que impusimos en aquel ejercicio.
Los datos del problema eran:
c = 12500 g/s.     m = 68100 g      t = 2.,4,6,8,10,12 s
Con estos datos obtuvimos unos valores de v, utilizando primero un método numérico aproximado, en forma de programa de computador, y utilizando después un método analítico, con el que obtuvimos el resultado exacto.
Ahora vamos a tomar como datos iniciales m = 68100 g, t=2,4,6,8,10,12, y la v obtenida por cada uno de los dos métodos en el tema 1, y vamos a calcular mediante un método numérico conocido como la iteración del punto fijo el valor de c que cumple la ecuación (2.4). En este ejemplo tomaremos como función de iteración
con lo que el algoritmo que presentamos a continuación sería equivalente al método de Newton.
Algoritmo del punto fijo.
Elegir la función g(x), el punto de partida x0, la tasa de error y el número máximo de iteraciones I.
Hacer K = 1 (contador de iteraciones).
Hacer x1 = g(x0).
Mientras ( | x1 - x0 | > error y K < I ) hacer
x0 = x1
x1 = g(x0)
K = K + 1
Fin_Mientras
Si K ³ I entonces "no converge"
si no entonces solución = x1.

Tabla 2.1. Valores de c hallados por el método del punto fijo para la v obtenida mediante el método numérico:
Precisión: 0.1
Punto inicial: a = 10
Función:
       

DATOS RESULTADO
Masa (g)
m
Tiempo (s)
t
Vel. (cm/s)
v
coef. roz.(g/s)
c
Iteraciones del punto fijo.
68100
2
1960.0
0
2
68100
4
3200.5
7155.0
4
68100
6
3985.6
9483.9
5
68100
8
4482.5
10605.1
5
68100
10
4796.9
11243.6
5
68100
12
4995.9
11641.1
6

Observamos que los valores de c obtenidos distan mucho del valor que se debería obtener, que es 12500 g/s, pero esto no se debe a un defecto del método del punto fijo, sino del método de diferencias divididas utilizado para aproximar la derivada de la velocidad que utilizamos en el tema 1 para hallar los valores de v. También podemos observar que en instantes de tiempo posteriores el valor de c se va aproximando al valor correcto.
En el tema 1 se propuso como ejercicio que se calculasen los valores de la velocidad con intervalos de tiempo menores que 2. Si realizaste ese ejercicio ahora puedes utilizar los valores que obtuviste, como entradas para el método del punto fijo, y observarás que el valor de c que se obtiene en este caso resulta más cercano al real.


Tabla 2.2. Valores de c hallados por el método del punto fijo para la v obtenida mediante el método analítico:
Precisión: 0.1
Punto inicial: a = 10
Función:
       
DATOS RESULTADO
Masa (g)
m
Tiempo (s)
t
Vel. (cm/s)
v
coef. roz.(g/s)
c
Iteraciones del punto fijo.
68100
2
1640.5
12499.9
4
68100
4
2776.9
12500.4
5
68100
6
3564.2
12499.8
5
68100
8
4109.5
12500.2
5
68100
10
4487.3
12500.1
5
68100
12
4749.0
12500.1
6

Tomando los valores de v calculados mediante el método analítico sí que obtenemos el valor exacto de c. La falta de una precisión absoluta tampoco se debe esta vez al método del punto fijo, sino al error que cometimos en el tema 1 al redondear y quedarnos sólo con el primer decimal del valor de v.
Como se aprecia en las dos tablas, utilizando el método del punto fijo obtenemos rápidamente una solución satisfactoria, en muy pocas iteraciones.
Se consigue una importante mejora de prestaciones utilizando este método cuando sea posible en vez de los métodos menos precisos y más costosos comentados antes, como por ejemplo los métodos gráficos




MATLAB Tutorial este lo estoy codificando para octave

 MATLAB Tutorial este lo estoy codificando para octave
Alexander Arias
30 de mayo de 2017
la herramienta de trabajo: octave-online.net

  http://mathcs.holycross.edu/~spl/MATLAB/matlab.html


MATLAB Tutorial

Steven Levandosky
Department of Mathematics
Stanford University
Copyright 2001



Contents

1. Introduction
2. Getting Started
3. Variables
4. Matrices and Vectors
5. Dot Products and Cross Products
6. Basic Matrix Operations
7. Reduced Row Echelon Form
8. Rank
9. Inverses
10. Eigenvectors and Eigenvalues
11. Componentwise Operations
12. Plotting Curves
13. Plotting Surfaces
14. Level Curves
15. Vector Fields
16. Symbolic Variables and Expressions
17. Solving Algebraic Equations
18. Derivatives
19. M-Files


1  Introduction

MATLAB, which stands for Matrix Laboratory, is a very powerful program for performing numerical and symbolic calculations, and is widely used in science and engineering, as well as in mathematics. This tutorial is designed to provide the reader with a basic understanding of how MATLAB works, and how to use it to solve problems in linear algebra and multivariable calculus. It is intended to complement the regular course materials. So, although we often recall many of the basic definitions and results, we assume the reader already has some familiarity with them. All of the commands in this document were executed using version 5.3, and should also work in version 6.

2  Getting Started

When MATLAB starts (either by typing matlab at the command prompt on a Unix machine, or running the executable on a PC or Mac) the MATLAB prompt
>>

appears. All MATLAB commands are executed from this prompt.
>> 2.3+4.2

ans =

    6.5000

By default MATLAB returns numerical expressions as decimals with 5 digits. The format function is used to change the format of the output. Type format rat to have MATLAB return rational expressions.
>> format rat
>> 5.1-3.3

ans =

     9/5     
 

To eliminate the extra spacing type format compact.
>> format compact
>> 5*7
ans =
     35    

The four basic operations of addition, subtraction, multiplication and division are performed using the symbols +,-,* and /, respectively. Exponentiation is performed by means of the symbol ^.
>> 2^7
ans =
   128

MATLAB has most standard mathematical functions built-in. The sqrt function computes the square root.
>> format long
>> sqrt(2)
ans =
   1.41421356237310

The basic trigonometric functions (cos, sin, tan, sec, csc, cot), their inverses (acos, asin, atan, asec, acsc, acot), the exponential function exp, and the natural logarithm log are also built-in. For instance, ln(4)+cos(p/6) is computed as follows.
>> log(4)+cos(pi/6)
ans =
   2.25231976490433

For information about any MATLAB function, type help followed by the name of the function.
>> help abs

 ABS    Absolute value.
    ABS(X) is the absolute value of the elements of X. When
    X is complex, ABS(X) is the complex modulus (magnitude) of
    the elements of X.
 
    See also SIGN, ANGLE, UNWRAP.

 Overloaded methods
    help sym/abs.m

To avoid having to retype long expressions use the up arrow key to scroll through lines previously typed. Typing one or more characters and then the up arrow key displays previous lines that begin with those characters. To exit MATLAB type quit.

3  Variables

To assign a value to a variable in MATLAB simply type the name of the variable, followed by the assignment operator, =, followed by the value.
>> x=7
x =
     7

Note that variable names in MATLAB are case sensitive, so X and x are not equal. We can perform all of the usual operations with x.
>> x^2-3*x+2
ans =
    30
>> log(x)
ans =
   1.94591014905531
>> sin(x)
ans =
   0.65698659871879

New variables may be defined using existing variables.
>> y=8*x
y =
    56

This, however, does not imply any permanent relationship between x and y. If we change x, the value of y does not change.
>> x=x+5
x =
    12
>> y
y =
    56

The command who returns a list of all variables in the current workspace, while whos returns the same list with more detailed information about each variable.
>> who

Your variables are:

ans  x    y    

>> whos
  Name      Size           Bytes  Class

  ans       1x1                8  double array
  x         1x1                8  double array
  y         1x1                8  double array

Grand total is 3 elements using 24 bytes

Notice that the size of each variable is 1×1. All variables in MATLAB are matrices. Scalars such as x and y are just 1×1 matrices. We will explain how to enter matrices in the next section. To clear one or more variables from the workspace, type clear followed by the names of the variables. Typing just clear clears all variables.
>> clear
>> who
>> x
??? Undefined function or variable 'x'.

4  Matrices and Vectors

To enter a matrix in MATLAB, use square brackets and separate entries within a row by spaces and separate rows using semicolons.
>> A=[2 1 -1 8; 1 0 8 -3; 7 1 2 4]
A =
     2     1    -1     8
     1     0     8    -3
     7     1     2     4

Often we do not want MATLAB to display a response, especially when dealing with very large matrices. To suppress the output, place a semicolon at the end of the line. Typing
>> B=[2 0 -3; -1 1 3];

will still define the variable B containing a 2×3 matrix, but MATLAB will not echo anything.
>> whos
  Name      Size           Bytes  Class

  A         3x4               96  double array
  B         2x3               48  double array
  v         3x1               24  double array

Grand total is 21 elements using 168 bytes

To view the contents of the variable B, just type its name.
>> B
B =
     2     0    -3
    -1     1     3

Vectors (column vectors) are simply matrices with a single column.
>> v = [ 2; 3; -4]
v =
     2
     3
    -4

A row vector is a matrix with a single row.
>> w=[3 -2 5 11]
w =
     3    -2     5    11

It is often necessary to define vectors with evenly spaced entries. In MATLAB, the colon (:) provides a shorthand for creating such vectors.
>> 2:5
ans =
     2     3     4     5

Typing j:i:k defines a row vector with increment i starting at j and ending at k.
>> 3:2:9
ans =
     3     5     7     9

Recall that the transpose of a matrix A is the matrix AT whose entry in row i column j is the same as the entry in row j column i of A. In MATLAB, A' represents the transpose of the matrix A.
>> A=[5 -2 9; 11 7 8]
A =
     5    -2     9
    11     7     8
>> A'
ans =
     5    11
    -2     7
     9     8

To define regularly spaced column vectors, we can take the transpose of a regularly spaced row vector.
>> [1:3:10]'
ans =
     1
     4
     7
    10

The entry in row i, column j of a matrix A is A(i,j).
>> A=[3 -2 7 8; 4 3 2 1; 10 15 -2 9]
A =
     3    -2     7     8
     4     3     2     1
    10    15    -2     9

>> A(3,2)
ans =
    15

It is also possible to view multiple entries within any row or column. For instance, the second and fourth entries in the third row are accessed as follows.
>> A(3,[2 4])
ans =
    15     9

Row i of A is A(i,:) and column j of A is A(:,j).
>> A(3,:)
ans =
    10    15    -2     9
>> A(:,3)
ans =
     7
     2
    -2

Next we display the first, second and fourth columns.
>> A(:,[1 2 4])
ans =
     3    -2     8
     4     3     1
    10    15     9

The entries of a vector (row or column) may be accessed using a single index.
>> w=[7; 13; 11]
w =
     7
    13
    11
>> w(2)
ans =
    13

Matrices with the same number of rows may be concatenated horizontally, and matrices with the same number of columns may be concatenated vertically.
>> A=[1 2 3; 4 5 6]
A =
     1     2     3
     4     5     6
>> B=[7 8; 9 10]
B =
     7     8
     9    10
>> [A B]
ans =
     1     2     3     7     8
     4     5     6     9    10
>> C=[7 8 9]
C =
     7     8     9
>> [A;C]
ans =
     1     2     3
     4     5     6
     7     8     9

To remove rows or columns from a matrix, simply redefine them to be empty matrices.
>> A=[ 4 7 2 1 3; 8 7 12 -2 5; 11 1 14 -2 0]
A =
     4     7     2     1     3
     8     7    12    -2     5
    11     1    14    -2     0
>> A(2,:)=[]
A =
     4     7     2     1     3
    11     1    14    -2     0
>> A(:,[1 3])=[]
A =
     7     1     3
     1    -2     0


5  Dot Products and Cross Products

The function dot computes the dot product of two vectors in Rn .
>> v=[7; 23; 15; 2], w=[5; -2; 1; -8]
v =
     7
    23
    15
     2
w =
     5
    -2
     1
    -8
>> dot(v,w)
ans =
   -12

Note that the dot product is symmetric.
>> dot(w,v)
ans =
   -12

Recall that the length of a vector v is ||v||={v·v}.
>> vlength=sqrt(dot(v,v))
vlength =
   28.4077

The length of a vector can also be found directly using the norm function.
>> norm(v)
ans =
   28.4077

Also recall that if q is the angle between two vectors v and w then v·w=||v||||w||cosq. Solving for the angle we have q = arccos((v·w)/||v||||w||).
>> theta=acos(dot(v,w)/(norm(v)*norm(w)))
theta =
    1.6144
>> theta*180/pi
ans =
   92.4971

So the angle between v and w is about 92.5. The function cross computes the cross product of two vectors in R3.
>> v=[3; 2; 1], w=[4; 15; 1]
v =
     3
     2
     1
w =
     4
    15
     1
>> x=cross(v,w)
x =
   -13
     1
    37

Cross products are anti-symmetric. That is, w×v=-v×w.
>> cross(w,v)
ans =
    13
    -1
   -37

The cross product v×w is orthogonal to both v and w. We can verify this by taking its dot product with both v and w. Recall that two vectors are orthogonal if and only if their dot product equals zero.
>> dot(x,v)
ans =
     0
>> dot(x,w)
ans =
     0


6  Basic Matrix Operations

Addition (and subtraction) of matrices of the same dimensions is performed componentwise.
>> A=[5 -1 2; 3 4 7]
A =
     5    -1     2
     3     4     7
>> B=[2 2 1; 5 0 3]
B =
     2     2     1
     5     0     3
>> A+B
ans =
     7     1     3
     8     4    10

Note that only matrices with the same dimensions may be summed.
>> C=[3 1; 6 4]
C =
     3     1
     6     4
>> A+C
??? Error using ==> +
Matrix dimensions must agree.

Scalar multiplication (and division by nonzero scalars) is also performed componentwise.
>> 2*A
ans =
    10    -2     4
     6     8    14

The * in scalar multiplication is not optional.
>> 2A
??? 2
    |
Missing operator, comma, or semi-colon.

Vector addition and scalar multiplication are performed in the same way.
>> v=[3; 5], w=[-2; 7]
v =
     3
     5
w =
    -2
     7
>> 10*v-5*w
ans =
    40
    15

The matrix product A*B is defined when A is m×n and B is n×k. That is, the number of columns of A must equal the number of rows of A. In this case the product A*B is an m×k matrix.
>> A=[3 1 7 2; 6 -3 4 2; 9 4 -1 -2]
A =
     3     1     7     2
     6    -3     4     2
     9     4    -1    -2
>> B=[1 2; 3 4; 5 6; 7 8]

B =
     1     2
     3     4
     5     6
     7     8
>> A*B
ans =
    55    68
    31    40
     2    12

The entry in row i, column j of A*B is the dot product of row i of A with column j of B.
>> dot(A(2,:),B(:,1))
ans =
    31

MATLAB produces an error message if the inner matrix dimensions do not agree.
>> B*A
??? Error using ==> *
Inner matrix dimensions must agree.

The exception to this rule is when one of the matrices is a 1×1 matrix, i.e. a scalar. In this case the product is interpreted as scalar multiplication.
>> C=[2]
C =
     2
>> A*C
ans =
     6     2    14     4
    12    -6     8     4
    18     8    -2    -4

Matrix-vector products are special cases of matrix products.
>> A=[13 -11 21; 16 9 10], v=[19; -7; 15]
A =
    13   -11    21
    16     9    10
v =
    19
    -7
    15
>> A*v
ans =
    639      
    391      

As above, the entries of A*v are the dot products of the rows of A with v.
>> [dot(A(1,:),v); dot(A(2,:),v)]
ans =
    639      
    391      

Also, the product A*v equals the linear combination of the columns of A whose coefficients are the components of v.
>> v(1)*A(:,1)+v(2)*A(:,2)+v(3)*A(:,3)
ans =
    639      
    391      

A square matrix may be multiplied by itself, and in this case it makes sense to take powers of the matrix. For instance, A^6 equals A*A*A*A*A*A.
>> A=[0 1; 1 1]
A =
     0     1
     1     1
>> A*A
ans =
     1     1
     1     2
>> A^6
ans =
     5     8
     8    13


7  Reduced Row Echelon Form

The rref command is used to compute the reduced row echelon form of a matrix.
>> A=[1 2 3 4 5 6; 1 2 4 8 16 32; 2 4 2 4 2 4; 1 2 1 2 1 2]
A =
     1     2     3     4     5     6
     1     2     4     8    16    32
     2     4     2     4     2     4
     1     2     1     2     1     2
>> rref(A)
ans =
     1     2     0     0    -4    -8
     0     0     1     0    -1    -6
     0     0     0     1     3     8
     0     0     0     0     0     0

Any problem that can be phrased in terms of a system of linear equations can thus be solved using rref. For instance, consider the following set of vectors.
>> v1=[1; 1; 1]; v2=[1; -2; 1]; v3=[1; 2; 3]; v4=[2; 3; 4]; v5=[1; -1; -3];

Suppose we want to write v5 as a linear combination of the other vectors. First we define the augmented matrix for the resulting system of equations x1v1+x2v2+x3v3+x4v4=v5.
>> A=[v1 v2 v3 v4 v5]
A =
     1     1     1     2     1
     1    -2     2     3    -1
     1     1     3     4    -3

The reduced row echelon form then yields the solution(s).
>> rref(A)
ans =
     1     0     0     1     3
     0     1     0     0     0
     0     0     1     1    -2

The variable x4 is a free variable, so let's choose x4=0. Then x1=3, x2=0 and x3=-2, and therefore v5=3v1-2v3. Let's check.
3*v1-2*v3
ans =
     1
    -1
    -3

Any other choice of x4 will result in a different way of writing v5 as a linear combination of the other vectors. Now suppose we want to write v2 as a linear combination of v1, v3, v4 and v5.
>> A=[v1 v3 v4 v5 v2]
A =
     1     1     2     1     1
     1     2     3    -1    -2
     1     3     4    -3     1
>> rref(A)
ans =
     1     0     1     3     0
     0     1     1    -2     0
     0     0     0     0     1

This time the third equation reduces to 0=1, so there are no solutions, and therefore v2 is not a linear combination of the other vectors. Another way to use rref is in the form [R,p]=rref(A), which defines R to be the reduced row echelon form of A and p to be the vector listing the columns of R which contain pivots.
>> A=[ 1 2 1 5; 1 2 2 6; 1 2 3 7; 1 2 4 8]
A =
     1     2     1     5
     1     2     2     6
     1     2     3     7
     1     2     4     8
>> [R,p]=rref(A)
R =
     1     2     0     4
     0     0     1     1
     0     0     0     0
     0     0     0     0
p =
     1     3

Extracting the pivot columns of A gives a basis for the column space of A.
>> A(:,p)
ans =
     1     1
     1     2
     1     3
     1     4

With the reduced row echelon form of A in hand we could easily find a basis for the null space of A. The command null does this for us.
>> null(A,'r')
ans =
    -2    -4
     1     0
     0    -1
     0     1

The 'r' stands for rational and tells MATLAB to find the null space from the reduced row echelon form of A. Without the 'r', MATLAB finds an orthonormal basis for the null space - that is, a basis consisting of mutually orthogonal unit vectors.
>> N=null(A)
N =
   -0.9608         0
    0.1601   -0.8165
   -0.1601   -0.4082
    0.1601    0.4082

To verify that this is an orthonormal basis we form the product N'*N. Since the rows of N' are the columns of N, the entry in row i, column j of N'*N is the dot product of column i and column j of N.
>> N'*N
ans =
    1.0000         0
         0    1.0000

The ones on the diagonal indicate that the columns of N are unit vectors, and the zeros indicate that they are orthogonal to each other. We can also use rref to find the inverse of an invertible matrix. Recall that a matrix A is invertible if and only if rref(A)=In, the n×n identity matrix, and that in this case rref[A | In]=[In | A-1]. For example, consider the following matrix.
>> A=[1 1 1; 1 2 3; 1 3 6]
A =
     1     1     1
     1     2     3
     1     3     6 

In MATLAB, the n×n identity matrix In is given by eye(n). Let's augment A by eye(3) and compute its reduced row echelon form.
>> B=[A eye(3)]
B =
     1     1     1     1     0     0
     1     2     3     0     1     0
     1     3     6     0     0     1
>> rref(B)
ans =
     1     0     0     3    -3     1
     0     1     0    -3     5    -2
     0     0     1     1    -2     1

So
>> Ainv=[3 -3 1; -3 5 -2; 1 -2 1]
Ainv =
     3    -3     1
    -3     5    -2
     1    -2     1

is the inverse of A. To verify this, recall that A-1A=AA-1=In.
>> Ainv*A
ans =
     1     0     0
     0     1     0
     0     0     1
>> A*Ainv
ans =
     1     0     0
     0     1     0
     0     0     1


8  Rank

To compute the rank of a matrix we use the rank command. We briefly recall some of the important facts regarding the rank of a matrix.
  • The rank of a matrix equals the dimension of its column space.
  • The columns of a matrix are linearly independent if and only if its rank equals the number of columns.
  • An n×n square matrix is invertible if and only if its rank equals n.
For example,
>> A=[1 2 1 4; 2 3 1 3; 3 2 1 2; 4 3 1 1]
A =
     1     2     1     4
     2     3     1     3
     3     2     1     2
     4     3     1     1
>> rank(A)
ans =
     3

Thus the column space of A has dimension 3 and the columns of A above are linearly dependent. Using rank we can determine which columns of A form a basis for its column space.
>> rank(A(:,[1 2 3]))
ans =
     3
>> rank(A(:,[1 2 4]))
ans =
     3
>> rank(A(:,[1 3 4]))
ans =
     2
>> rank(A(:,[2 3 4]))
ans =
     3

Thus any choice of three columns forms a basis for the column space of A except columns one, three and four. Next we use rank as a test for invertibility.
>> A=[11 -21 3; 8 2 1; 16 -12 5]
A =
    11   -21     3
     8     2     1
    16   -12     5
>> rank(A)
ans =
     3
>> B=[3 4 5;6 7 8;9 10 11]
B =
     3     4     5
     6     7     8
     9    10    11
>> rank(B)
ans =
     2

The matrix A is invertible, but B is not. Using rank it is possible to determine whether or not a given vector is in the column space of a matrix.
>> A=[5 8 -4; 3 19 11; -6 6 0; 12 4 1]
A =
     5     8    -4
     3    19    11
    -6     6     0
    12     4     1
>> v1=[21; 16; -7; 33],v2=[30; 7; 30; -16]
v1 =
    21
    16
    -7
    33
v2 =
    30
     7
    30
   -16
>> rank(A)
ans =
     3

So the column space of A is three-dimensional. Now consider the augmented matrix [A v]. If v is in the column space of A, then [A v] has rank 3. Otherwise [A v] has rank 4.
>> rank([A v1])
ans =
     4
>> rank([A v2])
ans =
     3

Thus v2 is in the column space of A, but v1 is not.

9  Inverses

The inverse of an invertible matrix A can be found by using either A^(-1) or inv(A).
>> A=[2 1 1; 1 2 2; 2 1 2]
A =
      2            1            1      
      1            2            2      
      2            1            2      
>> Ainv=inv(A)
Ainv =
     2/3         -1/3           0      
     2/3          2/3          -1      
     -1            0            1      

Let's verify the result.
>> A*Ainv
ans =
      1            0            0      
      0            1            0      
      0            0            1      
>> Ainv*A
ans =
      1            0            0      
      0            1            0      
      0            0            1      

MATLAB gives a warning message if the matrix is singular (not invertible).
>> B=[1 2 3;4 5 6;7 8 9]
B =
     1     2     3
     4     5     6
     7     8     9
>> inv(B)

Warning: Matrix is close to singular or badly scaled.
         Results may be inaccurate. RCOND = 2.055969e-018.
ans =
  1.0e+016 *
   -0.4504    0.9007   -0.4504
    0.9007   -1.8014    0.9007
   -0.4504    0.9007   -0.4504

Here MATLAB actually returns an inverse. To see that B is really singular, compute its rank.
>> rank(B)
ans =
     2

Since the rank of B is less than 3, B is singular. Also recall that a matrix is invertible if and only if its determinant is nonzero.
>> det(B)
ans =
     0

Unfortunately, there are invertible matrices which MATLAB regards as singular.
>> format long
>> C=[1.00000000000001 1; 1 .99999999999999]
C =
   1.00000000000001   1.00000000000000
   1.00000000000000   0.99999999999999
>> inv(C)
Warning: Matrix is singular to working precision.
ans =
   Inf   Inf
   Inf   Inf
>> rank(C)
ans =
     1
>> det(C)
ans =
     0
>> rref(C)
ans =
   1.00000000000000   0.99999999999999
                  0                  0

According to MATLAB, the matrix C has rank 1 and determinant zero, and is therefore singular. However, if we let e = 0.00000000000001, then det(C)=(1+e)(1-e)-1=-e2 0, so C is invertible. The problem is that in format long MATLAB is accurate to 15 places and therefore recognizes 1+e and 1-e as being different from 1, but recognizes
(1+e)(1-e)=1-e2 = 0.9999999999999999999999999999
as 1. This example should serve as a warning to not blindly accept everything that MATLAB tells us. To solve an equation of the form Ax=b where A is invertible, we simply multiply by the inverse of A to get x=A-1b.
>> A=[11 7 -6 8; 3 -1 12 15; 1 1 1 7; -4 6 1 8]
A =
    11     7    -6     8
     3    -1    12    15
     1     1     1     7
    -4     6     1     8
>> b=[10; -23; -13; 4]
b =
    10
   -23
   -13
     4
>> format rat
>> x=inv(A)*b
x =
      1      
      5      
      2      
     -3      

Let's verify this result.
>> A*x
ans =
     10      
    -23      
    -13      
      4      


10  Eigenvectors and Eigenvalues

The eig command is used to find the eigenvalues of a square matrix.
>> A=[ 3 1 1; 1 3 1; 1 1 3]
A =
     3     1     1
     1     3     1
     1     1     3
>> eig(A)
ans =
    2.0000
    2.0000
    5.0000
If A is diagonalizable, the eig command can also be used to find an eigenbasis, along with the diagonal matrix to which it is similar.
>> [Q,D]=eig(A)
Q =
   -0.8164   -0.0137    0.5774
    0.3963    0.7139    0.5774
    0.4201   -0.7001    0.5774
D =
    2.0000         0         0
         0    2.0000         0
         0         0    5.0000
Here, the columns of the matrix Q form an eigenbasis of A, and Q-1AQ=D. Let's check.
>> inv(Q)*A*Q
ans =
    2.0000         0    0.0000
    0.0000    2.0000    0.0000
   -0.0000    0.0000    5.0000
The matrix Q actually contains an orthonormal basis of eigenvectors.
>> Q'*Q
ans =
    1.0000    0.0000   -0.0000
    0.0000    1.0000   -0.0000
   -0.0000   -0.0000    1.0000
If we just wanted to find the eigenvectors in the ''usual'' way, we would use the null command.
>> C1=null(A-2*eye(3),'r')
C1 =
    -1    -1
     1     0
     0     1
>> C2=null(A-5*eye(3),'r')
C2 =
     1
     1
     1
Let's now check that these three vectors form an eigenbasis.
>> C=[C1 C2]
C =
    -1    -1     1
     1     0     1
     0     1     1
>> inv(C)*A*C
ans =
    2.0000   -0.0000    0.0000
         0    2.0000   -0.0000
         0         0    5.0000
Great! It worked.

11  Componentwise Operations

The componentwise product of two matrices A and B is the matrix A.*B whose entries are the products of the corresponding entries of A and B.
>> A=[ 1 2 3; 4 5 6]
A =
      1            2            3      
      4            5            6      
>> B=[ 3 2 1; -1 2 2]
B =
      3            2            1      
     -1            2            2      
>> A.*B
ans =
      3            4            3      
     -4           10           12      

Componentwise division and exponentiation are defined by A./B and A.^B, respectively. Each componentwise operation must make sense, or MATLAB will produce an error message.
>> A./B
ans =
     1/3           1            3      
     -4           5/2           3      
>> A.^B
ans =
      1            4            3      
     1/4          25           36      


12  Plotting Curves

The plot function is used to plot data in the plane. Given a vector x of x-coordinates x1 through xn and a vector y of y-coordinates y1 through yn, plot(x,y) graphs the points (x1,y1) through (xn,yn). By default these points are connected in order by straight line segments. For example, here is how one would plot the quadrilateral with vertices (0,0), (1,1), (4,2) and (5,-1).
>> x=[0 1 4 5 0];
>> y=[0 1 2 -1 0];
>> plot(x,y)

One can approximate the graph of a function by plotting a large number of points on the graph. Recall that j:i:k represents the row vector whose components range from j to k in increments of i. To plot the graph of y=x3 on the interval [-2,2], we first define a row vector whose components range from -2 to 2 in increments of .05.
>> x=-2:.05:2;

The vector x is therefore a 1 by 81 matrix. This can be seen by typing size(x). Next, we use componentwise exponentiation to define a vector of the same size as x whose components are the cubes of the components of x.
>> y=x.^3;

Typing y=x^3 would result in an error since x is not a square matrix. Finally we use the plot function to display the graph.
>> plot(x,y)

Now let's give our figure a title.
>> title('Graph of f(x)=x^3')

Parametric curves in the plane may be plotted in the same way. For example, to plot the curve r(t)=(2tcost/(t+1),2tsint/(t+1)) for t [0,4p], we first enter the vector of t values.
>> t=0:.1:4*pi;

Next we enter the x and y coordinates and plot the curve.
>> x=2*t.*cos(t)./(t+1);
>> y=2*t.*sin(t)./(t+1);

Notice that we used componentwise multiplication and division between expressions involving the vector t. Since scalar multiplication is already a componentwise operation, the scalar multiplication by 2 does not require the dot. Now we plot the curve.
>> plot(x,y);
>> title('(2t cos t/(t+1),2t sin t/(t+1))')

Notice that MATLAB automatically scales the axes so that the graph takes up the full screen. To see the graph to proper scale, type axis equal.
>> axis equal

To plot more than one curve in the same figure, type hold on. For instance, let's plot the two circles x2+y2=4 and (x-1)2+(y-1)2=1. These are parametrized, respectively, by r1(t)=(2cost,2sint) and r2(t)=(1+cost,1+sint) for t [0,2p].
>> t=0:pi/20:2*pi;
>> plot(2*cos(t),2*sin(t))
>> hold on
>> plot(1+cos(t),1+sin(t))
>> axis equal
>> title('The circles x^2+y^2=4 and (x-1)^2+(y-1)^2=1')

The three dimensional analogue of plot is plot3. For example, the parametric curve r(t)=(cos(t),sin(t),t) for t [0,8p] is plotted as follows.
>> t=0:.1:8*pi;
>> plot3(cos(t),sin(t),t)
>> title('(cos t,sin t,t)')

13  Plotting Surfaces

To plot the graph of a function f(x,y) over a rectangular domain
R=[a,b]×[c,d]={(x,y) | a x b and c y d},
we need to first create a grid of points within the domain using the function meshgrid.
For example, to subdivide the rectangle [0,4]×[0,3] into rectangles of width 1 and height .5, we first define vectors x and y which determine the spacing of the grid.
>> x=0:4
x =
     0     1     2     3     4
>> y=0:.5:3
y =
         0    0.5000    1.0000    1.5000    2.0000    2.5000    3.0000

Next meshgrid defines the points in the grid.
>> [X,Y]=meshgrid(x,y)
X =
     0     1     2     3     4
     0     1     2     3     4
     0     1     2     3     4
     0     1     2     3     4
     0     1     2     3     4
     0     1     2     3     4
     0     1     2     3     4
Y =
         0         0         0         0         0
    0.5000    0.5000    0.5000    0.5000    0.5000
    1.0000    1.0000    1.0000    1.0000    1.0000
    1.5000    1.5000    1.5000    1.5000    1.5000
    2.0000    2.0000    2.0000    2.0000    2.0000
    2.5000    2.5000    2.5000    2.5000    2.5000
    3.0000    3.0000    3.0000    3.0000    3.0000

These 7×5 matrices define the 35 points in the grid. The matrix X contains the x coordinates and Y contains the y coordinates. Suppose now that we want to plot the function f(x,y)=3x-2y. We then define the matrix Z of z coordinates.
>> Z=3*X-2*Y
Z =
     0     3     6     9    12
    -1     2     5     8    11
    -2     1     4     7    10
    -3     0     3     6     9
    -4    -1     2     5     8
    -5    -2     1     4     7
    -6    -3     0     3     6

Finally, we use surf to plot the surface.
>> surf(X,Y,Z)
>> title('Graph of f(x,y)=3x-2y')

It was actually not necessary in this example to define the variables x and y. We could have defined the grid directly by typing
>> [X,Y]=meshgrid(0:4,0:.5:3)

Also, if meshgrid is provided a single vector as its argument, it defines a square grid with the same spacing in x and y. So meshgrid(0:.5:2) is equivalent to meshgrid(0:.5:2,0.5:2). Next let's plot the graph of the function f(x,y)=x2y-2y over the rectangle [-2,2]×[-1,1]. We will use a grid consisting of squares with side length .1 and suppress the output so MATLAB does not display the resulting 11×21 matrices.
>> [X,Y]=meshgrid(-2:.1:2,-1:.1:1);

Next we use componentwise exponentiation and multiplication to define Z.
>> Z=(X.^2).*Y-2*Y;

Finally we plot the surface.
>> surf(X,Y,Z)
>> title('Graph of f(x,y)=x^2y-2y')

One issue to be aware of when plotting surfaces is division by zero. For instance, suppose we want to plot the graph of f(x,y)=xy/[(x2+y2)] over the square [-1,1]×[-1,1].
>> [X,Y]=meshgrid(-1:.1:1);
>> Z=X.*Y./sqrt(X.^2+Y.^2);
Warning: Divide by zero.

If we now try to plot the surface, the grid point at (0,0) is missing! To avoid such difficulties, we can simply shift the grid slightly so that (0,0) is not part of the grid.
>> [X,Y]=meshgrid(-.99:.1:1);
>> Z=X.*Y./sqrt(X.^2+Y.^2);
>> surf(X,Y,Z)
>> title('Graph of f(x,y)=xy/\surd(x^2+y^2)')
>> axis equal
Parametric surfaces are plotted similarly. Given a parametrization
r(u,v)=(x(u,v),y(u,v),z(u,v))
of some surface, where the domain for (u,v) is some rectangle, we first create a grid in the parameters u and v, and then define the x, y and z coordinates in terms of this meshgrid using the parametrization. For instance, the sphere of radius r centered at the origin in R3 is parametrized by
r(f,q)=(rsinfcosq rsinfsinq,rcosf)       0 f p,0 q 2p.
Let's use this to plot the unit sphere. First we define the meshgrid in the parameters f and q.
>> phi=0:pi/20:pi;
>> theta=0:pi/10:2*pi;
>> [Phi,Theta]=meshgrid(phi,theta);

Next we use the parametrization above, with r = 1.
>> X=sin(Phi).*cos(Theta);
>> Y=sin(Phi).*sin(Theta);
>> Z=cos(Phi);

Finally we plot the surface, and scale the axes so that it looks like a sphere!
>> surf(X,Y,Z)
>> axis equal
>> title('Unit sphere in {\bf R}^3')


14  Level Curves

There are several ways to plot level curves of a function of two variables. Consider for example the function f(x,y)=x2-y2. To simply plot the level curves of f in the plane, we use contour.
>> [X,Y]=meshgrid(-1:.1:1);
>> Z=X.^2-Y.^2;
>> contour(X,Y,Z)
>> title('Level curves of f(x,y)=x^2-y^2')

The following lines add labels to the level curves.
>> [C,h]=contour(X,Y,Z);
>> clabel(C,h)
>> title('Level curves of f(x,y)=x^2-y^2 with labels.')

To show the level curves in R3 at their actual height, use contour3.
>> contour3(X,Y,Z)
>> title('Level curves of f(x,y)=x^2-y^2 at actual height.')

To show the level curves below the graph of the function, use surfc.
>> surfc(X,Y,Z)
>> title('Level curves and graph of f(x,y)=x^2-y^2.')


15  Vector Fields

Recall that a vector field on Rn is a function F:RnRn, and that vector fields are represented graphically by placing the vector F(x) at each point x in Rn. In MATLAB, quiver(X,Y,U,V) plots vectors (U,V) at the points (X,Y). For example, the vector field F(x,y)=(-y,x) is shown below.
>> [X,Y]=meshgrid(-1:.2:1);
>> quiver(X,Y,-Y,X)
>> axis equal
>> axis([-1 1 -1 1])

Notice however that this plot is not quite accurate. The vector at (0.8,0) is certainly not (0,.8). MATLAB automatically scales the vectors so that they do not overlap. To modify this scaling use quiver(X,Y,U,V,s), where s is the desired scaling. Setting s=0 removes the automatic scaling and shows the ``correct'' picture.
>> quiver(X,Y,-Y,X,0)

An important example of a vector field is the gradient f of a scalar valued function f:RnR. We plot the gradient vector field of f(x,y)=x3-3x-2y2 as follows. First define a grid and enter the function.
>> [X,Y]=meshgrid(-2:.2:2,-1:.2:1);
>> Z=X.^3-3*X-2*Y.^2;

Next,
[DX,DY]=gradient(Z,.2,.2);

defines [DX,DY] to be (approximately) the gradient of f. The crucial thing here is that the second and third arguments agree with the spacing in the previous meshgrid. Finally, we use quiver to plot the field.
>> quiver(X,Y,DX,DY)
>> axis equal
>> axis([-2 2 -1 1])
>> title('Gradient vector field of f(x,y)=x^3-3x-2y^2')

Now let's plot the level curves of f on the same plot. Using a finer grid makes the contour plot more accurate.
>> [X,Y]=meshgrid(-2:.1:2,-1:.1:1);
>> Z=X.^3-3*X-2*Y.^2;
>> contour(X,Y,Z,10)
>> title('Gradient vector field and level curves of f(x,y)=x^3-3x-2y^2') 

Notice that the gradient vectors are perpendicular to the level curves, as expected. Now recall that a point at which the gradient of f vanishes is called a critical point of f. From the figures it appears that (-1,0) and (1,0) are critical points. Also recall that the gradient of f points in the direction of greatest increase of f. Since all the gradient vectors near (-1,0) point toward (-1,0) we conclude that f must have a local maximum at (-1,0). At (1,0), some gradient vectors nearby point away from (1,0) and some point toward (1,0). This indicates that f has a saddle at (1,0). This can be seen in the graph of f.
>> hold off
>> surf(X,Y,Z)
>> title('Graph of f(x,y)=x^3-3x-2y^2')


16  Symbolic Variables and Expressions

One of the more powerful packages in MATLAB is the Symbolic Math Toolkit, which contains a number of functions for performing symbolic computations. Symbolic variables are defined using the sym function.
>> x=sym('x')
x =
x

This defines a symbolic variable named x whose value is 'x'. The two names need not be the same. For instance x=sym('y') makes sense, but is a bit confusing, especially if the variable y is defined. The function syms provides a shorthand for defining symbolic variables. The line
>> syms x y z

is equivalent to the three lines x=sym('x'), y=sym('y') and z=sym('z'). Using symbolic variables, we can create symbolic expressions.
>> S=x^2-y^2
S =
x^2-y^2

This defines the symbolic variable S containing the expression x^2-y^2. Let's factor this expression.
>> factor(S)
ans =
(x-y)*(x+y)

Next let's cube S and expand the result.
>> S^3
ans =
(x^2-y^2)^3
>> expand(ans)
ans =
x^6-3*x^4*y^2+3*x^2*y^4-y^6

The simplify function is quite useful in dealing with symbolic expressions.
>> S=(x^3-4*x)/(x^2+2*x)
S =
(x^3-4*x)/(x^2+2*x)
>> simplify(S)
ans =
x-2

Symbolic expressions may also be vectors and matrices.
>> syms a b
>> A=[cos(a) -sin(a); sin(a) cos(a)]
A =
[  cos(a), -sin(a)]
[  sin(a),  cos(a)]

This is the matrix for counterclockwise rotation through angle a. Let's multiply this by the matrix for rotation through angle b.
 
>> B=[cos(b) -sin(b); sin(b) cos(b)]
B =
[  cos(b), -sin(b)]
[  sin(b),  cos(b)]
>> C=A*B
C =
[  cos(a)*cos(b)-sin(a)*sin(b), -cos(a)*sin(b)-sin(a)*cos(b)]
[  sin(a)*cos(b)+cos(a)*sin(b),  cos(a)*cos(b)-sin(a)*sin(b)]

This ought to be the matrix for rotation through angle a+b (Why?).
>> simplify(C)
ans =
[  cos(a)*cos(b)-sin(a)*sin(b), -cos(a)*sin(b)-sin(a)*cos(b)]
[  sin(a)*cos(b)+cos(a)*sin(b),  cos(a)*cos(b)-sin(a)*sin(b)]

Hmm, simplify did not do anything. Another option is to use simple, which looks for the shortest equivalent expression.
>> D=simple(C)
D =
[  cos(a+b), -sin(a+b)]
[  sin(a+b),  cos(a+b)]

As expected, this is the matrix for the rotation through angle a+b. It is tempting to think of symbolic expressions as functions of the symbolic variables they contain. They are not. Suppose we want to enter f(x,y)=(4x2-1)e-x2-y2 as a symbolic expression and compute f(1,2).
>> syms x y
>> f=(4*x^2-1)*exp(-x^2-y^2)
f =
(4*x^2-1)*exp(-x^2-y^2)
>> f(1,2)
??? Index exceeds matrix dimensions.

Since f is not a function, but a variable, MATLAB reads f(1,2) as the entry in row 1, column 2 of f. But f only has one entry, the expression (4*x^2-1)*exp(-x^2-y^2). To evaluate a symbolic expression we need to substitute values for its symbolic variables. This is done using the subs function.
>> subs(f,{x,y},{1,2})
ans =
    0.0202

It is not necessary to substitute for all variables in a symbolic expression.
>> subs(f,x,3)
ans =
35*exp(-9-y^2)

The substituted values may also be symbolic expressions.
>> syms u v
>> subs(f,{x,y},{u+v,u-v})
ans =
(4*(u+v)^2-1)*exp(-(u+v)^2-(u-v)^2)

The subs command thus provides a method of forming composite functions. We remark here that there is a way to define functions in MATLAB that behave in the usual manner. This is done using the inline command. For instance, the function g(x,y)=x2-3xy+2 is defined as follows.
>> g=inline('x^2-3*x*y+2')
g =
     Inline function:
     g(x,y) = x^2-3*x*y+2

Now we can evaluate g(2,3) in the usual way.
g(2,3)
ans =
   -12

The disadvantage of inline functions is that they cannot be manipulated symbolically.
>> g^2
??? Error using ==> ^
Function '^' not defined for variables of class 'inline'.


17  Solving Algebraic Equations

The solve command is used to find solutions of equations involving symbolic expressions.
>> solve('sin(x)+x=5')
ans =
5.6175550052726989176213921571114

In expressions with more than one variable, we can solve for one or more of the variables in terms of the others. Here we find the roots of the quadratic ax2+bx+c in x in terms of a, b and c. By default solve sets the given expression equal to zero if an equation is not given.
>> solve('a*x^2+b*x+c','x')
ans =
[ 1/2/a*(-b+(b^2-4*a*c)^(1/2))]
[ 1/2/a*(-b-(b^2-4*a*c)^(1/2))]

Systems of equations can also be handled by solve.
>> S=solve('x+y+z=1','x+2*y-z=3')
S = 
    x: [1x1 sym]
    y: [1x1 sym]

The variable S contains the solution, which consists of x and y in terms of z.
>> S.x
ans =
-3*z-1
>> S.y
ans =
2*z+2

Now let's find the points of intersection of the circles x2+y2=4 and (x-1)2+(y-1)2=1.
>> S=solve('x^2+y^2=4','(x-1)^2+(y-1)^2=1')
S = 
    x: [2x1 sym]
    y: [2x1 sym]
>> [S.x S.y]
ans =
[ 5/4-1/4*7^(1/2), 5/4+1/4*7^(1/2)]
[ 5/4+1/4*7^(1/2), 5/4-1/4*7^(1/2)]

The points of intersection are therefore ((5-7)/4,(5+7)/4) and ((5+7)/4,(5-7)/4).

18  Derivatives

Differentiation of a symbolic expression is performed by means of the function diff. For instance, let's find the derivative of f(x)=sin(ex).
>> syms x
>> f=sin(exp(x))
f =
sin(exp(x))
>> diff(f)
ans =
cos(exp(x))*exp(x)

The nth derivative of f is diff(f,n).
>> diff(f,2)
ans =
-sin(exp(x))*exp(x)^2+cos(exp(x))*exp(x)

To compute the partial derivative of an expression with respect to some variable we specify that variable as an additional argument in diff. Let f(x,y)=x3y4+ysinx.
>> syms x y
>> f=x^3*y^4+y*sin(x)
f =
x^3*y^4+y*sin(x)

First we compute f/x.
>> diff(f,x)
ans =
3*x^2*y^4+y*cos(x)

Next we compute f/y.
>> diff(f,y)
ans =
4*x^3*y^3+sin(x)

Finally we compute 3 f/x3.
>> diff(f,x,3)
ans =
6*y^4-y*cos(x)

The Jacobian matrix of a function f:RnRm can be found directly using the jacobian function. For example, let f:R2R3 be defined by f(x,y)=(sin(xy),x2+y2,3x-2y).
>> f=[sin(x*y); x^2+y^2; 3*x-2*y]
f =
[ sin(y*x)]
[  x^2+y^2]
[  3*x-2*y]
>> Jf=jacobian(f)
Jf =
[ cos(y*x)*y, cos(y*x)*x]
[        2*x,        2*y]
[          3,         -2]

In the case of a linear transformation, the Jacobian is quite simple.
>> A=[11 -3 14 7;5 7 9 2;8 12 -6 3]
A =
    11    -3    14     7
     5     7     9     2
     8    12    -6     3
>> syms x1 x2 x3 x4
>> x=[x1;x2;x3;x4]
x =
[ x1]
[ x2]
[ x3]
[ x4]
>> T=A*x
T =
[ 11*x1-3*x2+14*x3+7*x4]
[   5*x1+7*x2+9*x3+2*x4]
[  8*x1+12*x2-6*x3+3*x4]

Now let's find the Jacobian of T.
>> JT=jacobian(T)
JT =
[ 11, -3, 14,  7]
[  5,  7,  9,  2]
[  8, 12, -6,  3]

The Jacobian of T is precisely A. Next suppose f:RnR is a scalar valued function. Then its Jacobian is just its gradient. (Well, almost. Strictly speaking, they are the transpose of one another since the Jacobian is a row vector and the gradient is a column vector.) For example, let f(x,y)=(4x2-1)e-x2-y2.
>> syms x y real
>> f=(4*x^2-1)*exp(-x^2-y^2)
f =
(4*x^2-1)*exp(-x^2-y^2)
>> gradf=jacobian(f)
gradf =
[ 8*x*exp(-x^2-y^2)-2*(4*x^2-1)*x*exp(-x^2-y^2), -2*(4*x^2-1)*y*exp(-x^2-y^2)]
Next we use solve to find the critical points of f.
>> S=solve(gradf(1),gradf(2));
>> [S.x S.y]

ans =
[            0,            0]
[  1/2*5^(1/2),            0]
[ -1/2*5^(1/2),            0]

Thus the critical points are (0,0), (5/2,0) and (-5/2,0). The Hessian of a scalar valued function f:RnR is the n×n matrix of second order partial derivatives of f. In MATLAB we can obtain the Hessian of f by computing the Jacobian of the Jacobian of f. Consider once again the function f(x,y)=(4x2-1)e-x2-y2.
>> syms x y real
>> Hf=jacobian(jacobian(f));
>> Hf=simple(Hf)
Hf =
[2*exp(-x^2-y^2)*(2*x+1)*(2*x-1)*(2*x^2-5),  4*x*y*exp(-x^2-y^2)*(-5+4*x^2)]
[4*x*y*exp(-x^2-y^2)*(-5+4*x^2), 2*exp(-x^2-y^2)*(-1+2*y^2)*(2*x+1)*(2*x-1)]

We can now use the Second Derivative Test to determine the type of each critical point of f found above.
>> subs(Hf,{x,y},{0,0})
ans =
    10     0
     0     2
>> subs(Hf,{x,y},{1/2*5^(1/2),0})
ans =
   -5.7301         0
         0   -2.2920
>> subs(Hf,{x,y},{-1/2*5^(1/2),0})
ans =
   -5.7301         0
         0   -2.2920

Thus f has a local minimum at (0,0) and local maxima at the other two critical points. Evaluating f at the critical points gives the maximum and minimum values of f.
>> subs(f,{x,y},{0,0})
ans =
    -1
>> subs(f,{x,y},{'1/2*5^(1/2)',0})
ans =
4*exp(-5/4)
>> subs(f,{x,y},{'-1/2*5^(1/2)',0})
ans =
4*exp(-5/4)

Thus the minimum value of f is f(0,0)=-1 and the maximum value is f(5/2,0)=f(-5/2,0)=4e-5/4. The graph of f is shown below.
As our final example, we solve a Lagrange multiplier problem. For f(x,y)=xy(1+y) let's find the maximum and minimum of f on the unit circle x2+y2=1. First we enter the function f and the constraint function g(x,y)=x2+y2-1.
>> syms x y mu
>> f=x*y*(1+y)
f =
x*y*(1+y)
>> g=x^2+y^2-1
g =
x^2+y^2-1

Next we solve the Lagrange multiplier equations f(x,y)-mg(x,y)=0 and constraint equation g(x,y)=0 for x, y and m.
>> L=jacobian(f)-mu*jacobian(g)
L = [ y*(1+y)-2*mu*x, x*(1+y)+x*y-2*mu*y]
>> S=solve(L(1),L(2),g)
S = 
    mu: [5x1 sym]
     x: [5x1 sym]
     y: [5x1 sym]     

Next let's view the critical points found. We can ignore m now.
>> [S.x S.y]
ans =
[  1/6*(22-2*13^(1/2))^(1/2),           1/6+1/6*13^(1/2)]
[ -1/6*(22-2*13^(1/2))^(1/2),           1/6+1/6*13^(1/2)]
[  1/6*(22+2*13^(1/2))^(1/2),           1/6-1/6*13^(1/2)]
[ -1/6*(22+2*13^(1/2))^(1/2),           1/6-1/6*13^(1/2)]
[                          0,                         -1]

Next we need to evaluate f at each of these points.
>> values=simple(subs(f,{x,y},{S.x,S.y}))
values =
[    1/216*(22-2*13^(1/2))^(1/2)*(1+13^(1/2))*(7+13^(1/2))]
[   -1/216*(22-2*13^(1/2))^(1/2)*(1+13^(1/2))*(7+13^(1/2))]
[  1/216*(22+2*13^(1/2))^(1/2)*(-1+13^(1/2))*(-7+13^(1/2))]
[ -1/216*(22+2*13^(1/2))^(1/2)*(-1+13^(1/2))*(-7+13^(1/2))]
[                                                        0]

Finally we convert these into decimal expressions to identify the maximum and minimum. This is done using the double command.
>> double(values)
ans =
    0.8696
   -0.8696
   -0.2213
    0.2213
         0

Thus the maximum of f is about 0.8696 and the minimum is about -0.8696.

19  M-Files

MATLAB can also be used as a programming language. MATLAB programs are called M-files, and are saved with the extension .m. There are two types of M-files, scripts and functions. We will only discuss scripts here. A MATLAB script is a program which simply executes lines of MATLAB code. Scripts are particularly useful for tasks that require several lines of code. Rather than retyping every line when we want to make a small change, we can simply change one line of the script. A script consists of a plain text file with a list of MATLAB commands that we wish to execute. Here is an example of a script.
% <-- The % is for comments. 
% MATLAB ignores everything following it on the same line.
% test.m

A=[1 2; 3 4]
B=[5 6; 7 8]
A+B


After creating a file containing the text above, we save it with the filename test.m. In MATLAB we access this file by typing test. Note that, in order for this to work we must be sure that the current directory in MATLAB contains the file. The Unix commands ls (list contents of current directory), cd (change directory) and pwd (list name of current directory) all work within MATLAB.
>> test
A =
     1     2
     3     4
B =
     5     6
     7     8
ans =
     6     8
    10    12

MATLAB executes the commands in the M-file in order, as if we had typed them within MATLAB. We can also do loops within a script.
% sumsquares.m
% sums the first n squares up to n=10

s=0;
for n=1:10
   s=s+n^2
end

Here is what this looks like in MATLAB.
>> sumsquares
s =
     1
s =
     5
s =
    14
s =
    30
s =
    55
s =
    91
s =
   140
s =
   204
s =
   285
s =
   385

Here's one last example to try. It shows an animation of the curve r(t)=(2tcost/(t+1),2tsint/(t+1)) being plotted. See the Plotting Curves section for details on the commands used.
% curve.m
% Shows animation of a parametric curve being plotted.

hold on

for T=0:.1:4*pi
   t=[T T+.1];
   plot(2*t.*cos(t)./(t+1),2*t.*sin(t)./(t+1))
   axis equal
   axis([-2 2 -2 2])
   axis off
   pause(.01)
end




File translated from TEX by TTH, version 2.92.
On 23 Sep 2001, 23:14.