Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Autor:JosMaraValienteCifuentes
TrabajorealizadodentrodeunProyectoFindeCarreradirigidopor
CarlosMedranoSnchez
enlaE.U.PolitcnicadeTeruel
Ao2006
Licencia
Copyright(c)2006JosMaraValienteCifuentes
Manual
De
GNU Octave
Pg -1-
Manual de Iniciacin a GNU Octave
1. Operaciones Bsicas
1.1. Operaciones con matrices y vectores
1.1.1. Introduccin de matrices desde el teclado
1.1.2. Operaciones con matrices
1.1.3. Tipos de datos
1.1.3.1. Nmeros reales de doble precisin
1.1.3.2. Nmeros Complejos
1.1.3.3. Cadenas de caracteres
1.1.3.4. Otras formas de definir matrices
1.1.3.4.1 Tipos de matrices predefinidos
1.1.3.4.2 Formacin de una matriz a partir de otras
1.1.3.4.3 Direccionamiento de vectores y matrices a partir de
vectores
1.1.3.4.4 Operador <<Dos Puntos>> (:)
1.1.3.4.5 Definicin de matrices y vectores desde fichero
1.1.3.5. Operadores Relacionales
1.1.3.6. Operadores Lgicos
1.2. Funciones de Librera
1.2.1 Caractersticas Generales de las funciones de librera
1.2.2. Funciones matemticas elementales que operan de modo escalar
1.2.3. Funciones que actan sobre matrices
1.2.3.1 Funciones elementales
1.2.3.2 Funciones Especiales
1.2.3.3 Funciones de Factorizacin y/o Descomposicin Matricial
1.3. Ms sobre operadores relacionales con vectores y matrices
1.4. Otras funciones que actan sobre vectores y matrices
2. Otros tipos de datos de GNU Octave
2.1. Cadenas de caracteres
2.2 Hipermatrices (arrays de ms de dos dimensiones)
2.2.1 Definicin de Hipermatrices
Pg -2-
Manual de Iniciacin a GNU Octave
2.3 Estructuras
2.3.1 Creacin de Estructuras
2.3.2 Funciones para operar con Estructuras
2.4 Vectores o matrices de celdas (Cell Array)
2.4.1 Creacin de vectores y matrices de Celdas
2.4.2 Funciones para trabajar con vectores y matrices de celda
3. Programacin en GNU Octave
3.1. Bifurcaciones y bucles
3.1.1. Sentencia IF
3.1.2. Sentencia SWITCH
3.1.3. Sentencia FOR
3.1.4. Sentencia DO-UNTIL
3.1.5. Sentencia WHILE
3.1.6. Sentencia BREAK y CONTINUE
3.2 Ficheros *.m
3.2.1 Ficheros de Comandos (SCRIPTS)
3.2.2 Definicin de Funciones
3.2.3. HELP para las funciones de usuario
4. Grficos bidimensionales
4.1 Funciones grficas 2D elementales
4.1.1 Funcin PLOT
4.1.2 Estilos de Lnea y Marcadores para PLOT
4.1.3 Aadir Lneas a un grfico ya existente
4.1.4 Comando SUBPLOT
4.1.5 Control de los Ejes
4.2 Control de ventanas grficas: Funcin Figure
4.3 Otras funciones grficas 2-D
5. Grficos tridimensionales
5.1 Tipos de funciones grficas tridimensionales
5.1.1 Dibujo de lneas: Funcin PLOT3
5.1.2 Dibujo de mallados: Funciones MESHGRID, MESH Y SURF
5.1.3 Dibujo de lneas de contorno: Funcin CONTOUR
5.2. Elementos Generales: Ejes, Puntos de vista, lneas ocultas,
Pg -3-
Manual de Iniciacin a GNU Octave
Pg -4-
Manual de Iniciacin a GNU Octave
1. Operaciones Bsicas
Las matrices y vectores son variables del programa cuyos nombres podemos
definir, siempre y cuando no utilicemos los caracteres que el programa tiene como
caracteres prohibidos.
Para definir una matriz en GNU Octave se determina el nmero de filas y de
columnas en funcin del nmero de elementos que se proporcionan (o se utilizan). Las
matrices se definen por filas; los elementos de una misma fila estn separados por
blancos o comas, mientras que las filas estn separadas por pulsaciones intro o por
caracteres punto y coma (;). Tomemos como ejemplo:
octave:31> a=[1 1; 2 5]
Cuya salida ser:
a =
1 1
2 5
A partir de este momento la matriz a est disponible para hacer cualquier tipo de
operacin con ella (adems de valores numricos, en la definicin de una matriz o
vector se pueden utilizar expresiones y funciones matemticas). Por ejemplo, una
Pg -5-
Manual de Iniciacin a GNU Octave
1 2
1 5
Como el resultado de la operacin no ha sido asignado a ninguna otra matriz,
GNU Octave utiliza un nombre de variable por defecto (ans, de answer), que contiene
el resultado de la ltima operacin. La variable ans puede ser utilizada como operando
en la siguiente expresin que se introduzca. Tambin podra haberse asignado el
resultado a otra matriz llamada b.
Ahora vamos a definir una matriz b diferente para hacer operaciones bsicas
con estas 2 matrices:
octave:32> b=[7 6; 8 3]
b =
7 6
8 3
Comenzamos con las operaciones ms bsicas que podemos encontrar, la suma
y la resta de matrices:
octave:33> a + b
ans =
8 7
10 8
octave:34> a -b
ans =
-6 -5
-6 2
Pg -6-
Manual de Iniciacin a GNU Octave
octave:35> a * b
ans =
15 9
54 27
Tambin podemos utilizar una multiplicacin elemento a elemento, que aunque
no tiene demasiado sentido como multiplicacin de matrices, si que es muy utilizable en
el caso de que la matriz no sea ms que un conjunto ordenado de valores.
octave:36> a .* b
ans =
7 6
16 15
A continuacin vamos a definir una nueva matriz a a partir de una funcin que
genera valores aleatorios entre 0 y 1.
octave:4> a=rand(3); #generar una matriz aleatoria de 3x3
octave:5> a
a =
Vamos ahora a crear una matriz 3x3 para realizar nuevos clculos a partir de una
matriz ms manejable si queremos comprobar a mano los datos que creamos.
octave:6> a=[1 2 1;1 2 3;4 3.4 4.5]
a =
Pg -7-
Manual de Iniciacin a GNU Octave
2 0 0
octave:50> b=[2 0 0]
b =
2
0
0
Como podemos observar, podemos definir vectores fila y vectores columna, con
slo hacer la traspuesta del vector en la definicin. Tambin podemos definir un vector
columna como si hicieramos una matriz de 1xn
octave:46> b=[1;0];
Como podemos ver, no hemos obtenido resultado tras realizar la operacin; esto
es debido a que hemos puesto un ; al final de la lnea de comando, esto hace que no
salga por pantalla lo que hemos ejecutado, cosa que resulta muy til cuando las
Pg -8-
Manual de Iniciacin a GNU Octave
matrices/vectores son de un nmero muy grande (100, 1000, ) y por lo tanto, difciles
de manejar visualmente.
En GNU Octave se accede a los elementos de un vector poniendo el ndice entre
parntesis (por ejemplo x(3) x(i)). Los elementos de las matrices se acceden poniendo
los dos ndices entre parntesis, separados por una coma (por ejemplo A(1,2) A(i,j)).
Las matrices se almacenan por columnas (aunque se introduzcan por filas, como se ha
dicho antes), y teniendo en cuenta esto puede accederse a cualquier elemento de una
matriz con un slo subndice. Por ejemplo, si A es una matriz (3x3) se obtiene el mismo
valor escribiendo A(1,2) que escribiendo A(4).
Pg -9-
Manual de Iniciacin a GNU Octave
GNU Octave puede operar con matrices por medio de operadores y por medio
de funciones. Se han visto ya los operadores suma (+), producto (*) y traspuesta ('), as
como la funcin invertir inv( ). Los operadores matriciales de GNU OCTAVE son los
siguientes:
+ adicin o suma
sustraccin o resta
* multiplicacin
' traspuesta
^ potenciacin
\ divisin-izquierda
/ divisin-derecha
.* producto elemento a elemento
./ y .\ divisin elemento a elemento
.^ elevar a una potencia elemento a elemento
Estos operadores se aplican tambin a las variables o valores escalares, aunque
con algunas diferencias. Todos estos operadores son coherentes con las
correspondientes operaciones matriciales: no se puede por ejemplo sumar matrices que
no sean del mismo tamao. Si los operadores no se usan de modo correcto se obtiene un
mensaje de error.
Veamos un ejemplo del uso del divisor:
octave:45> #vamos a resolver un sistema de ecuaciones
octave:45> #x+y=1
octave:45> #2x+5y=0
octave:45> a=[1 1;2 5];
octave:46> b=[1;0];
octave:47> x=inv(a)*b
x =
1.66667
-0.66667
Pg -10-
Manual de Iniciacin a GNU Octave
1.66667
-0.66667
Vase el siguiente ejemplo de tres ecuaciones formadas por una recta que no
pasa por el origen y los dos ejes de coordenadas:
1 2
1 0
0 1
b =
2
0
0
0.33333
0.66667
resto =
-0.33333
0.33333
0.66667
Pg -11-
Manual de Iniciacin a GNU Octave
0.185185 -0.037037
1.259259 -0.851852
octave:38> a\b
ans =
9.0000 9.0000
-2.0000 -3.0000
Si los operadores / y \ van precedidos de un . La operacin se realiza elemento
a elemento:
octave:39> a./b
ans =
0.14286 0.16667
0.25000 1.66667
octave:40> a.\b
ans =
7.00000 6.00000
4.00000 0.60000
Podemos comprobar que premultiplicar con / es lo mismo que postmultiplicar con
\ .
octave:41> b./a
ans =
7.00000 6.00000
4.00000 0.60000
Pg -12-
Manual de Iniciacin a GNU Octave
GNU Octave trabaja siempre con el tipo Real de doble precisin, sobre el que se
implementan el resto de tipos, avanzados o no. Este tipo de dato se guarda con un
tamao de 8 bytes, que tiene un tamao de 15 cifras exactas. Adems del tipo Real,
podremos trabajar con strings, matrices, hipermatrices y estructuras ms avanzadas.
As pues, para GNU Octave el infinito se representa como inf Inf. GNU
Octave tiene tambin una representacin especial para los resultados que no estn
definidos como nmeros. Por ejemplo, ejectense los siguientes comandos y obsrvense
las respuestas obtenidas:
octave:51> 0/0
warning: division by zero
ans = NaN
Pg -13-
Manual de Iniciacin a GNU Octave
nmero sumado a un NaN da otro NaN. GNU Octave tiene esto en cuenta. Algo
parecido sucede con los Inf.
Podemos encontrar 3 variables predefinidas por GNU Octave que nos dan los
valores mximos y mnimos de este tipo de datos:
eps devuelve la diferencia entre 1.0 y el nmero de coma flotante
inmediatamente superior. Da una idea de la precisin o nmero de cifras
almacenadas. En un computador, eps vale 2.2204e-016.
realmin devuelve el nmero ms pequeo con que se puede trabajar
(2.2251e-308)
realmax devuelve el nmero ms grande con que se puede trabajar
(1.7977e+308)
Pg -14-
Manual de Iniciacin a GNU Octave
Pg -15-
Manual de Iniciacin a GNU Octave
pulsar intro. Tambin se pueden incluir varias expresiones en una misma lnea
separndolas por comas (,) o puntos y comas (;). Si una expresin termina en punto y
coma (;) su resultado se calcula, pero no se escribe en pantalla. Esta posibilidad es muy
interesante, tanto para evitar la escritura de resultados intermedios, como para evitar la
impresin de grandes cantidades de nmeros cuando se trabaja con matrices de gran
tamao.
A semejanza de C, GNU OCTAVE distingue entre maysculas y minsculas
en los nombres de variables. A diferencia del lenguaje C, no hace falta declarar las
variables que se vayan a utilizar. Esto hace que se deba tener especial cuidado con no
utilizar nombres errneos en las variables, porque no se recibir ningn aviso del
ordenador. Cuando se quiere tener una relacin de las variables que se han utilizado en
una sesin de trabajo se puede utilizar el comando who. Existe otro comando llamado
whos que proporciona adems informacin sobre el tamao, la cantidad de memoria
ocupada y el carcter real o complejo de cada variable.
Pg -16-
Manual de Iniciacin a GNU Octave
1 0
0 1
zeros(3,5) forma una matriz de ceros de tamao (3x5)
octave:83> zeros(3,5)
ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0
0 0
ones(3) forma una matriz de unos de tamao (3x3)
ones(3,4) idem de tamao (3x4)
octave:87> ones(3,4)
ans =
1 1 1 1
1 1 1 1
1 1 1 1
Pg -17-
Manual de Iniciacin a GNU Octave
Columns 1 through 8:
Column 9:
10.0000
octave:92> magic(3)
ans =
8 1 6
3 5 7
4 9 2
compan(pol) construye una matriz cuyo polinomio caracterstico tiene
como coeficientes los elementos del vector pol (ordenados de mayor
grado a menor).
octave:100> compan([1 2 1])
ans =
-2 -1
1 0
Hay ms tipos predefinidos de matrices, podemos encontrar en la ayuda todos
estos tipos y otros muchos ms con solo hacer help i matrix.
Pg -18-
Manual de Iniciacin a GNU Octave
0 0 0
0 0 0
0 0 0
ones(size(A)) dem con unos
A=diag(x) forma una matriz diagonal A cuyos elementos diagonales son
los elementos de un vector ya existente x.
x=diag(A) forma un vector x a partir de los elementos de la diagonal de
una matriz ya existente A.
Pg -19-
Manual de Iniciacin a GNU Octave
octave:111> diag(a)
ans =
1
2
5
diag(diag(A)) crea una matriz diagonal a partir de la diagonal de la
matriz A.
octave:112> diag(diag(a))
ans =
1 0 0
0 2 0
0 0 5
triu(A) forma una matriz triangular superior a partir de una matriz A (no
tiene por qu ser cuadrada).
octave:110> triu(a)
ans =
1 2 1
0 2 5
0 0 5
tril(A) dem con una matriz triangular inferior.
octave:109> tril(a)
ans =
1 0 0
3 2 0
6 7 5
Pg -20-
Manual de Iniciacin a GNU Octave
1 5 5
2 2 7
1 3 6
6 7 5
3 2 5
1 2 1
0 0 0 0
0 1 0 1
0 0 1 1
0 1 1 0
Pg -21-
Manual de Iniciacin a GNU Octave
octave:127> a=rand(2,5)
a =
octave:134> a(2,3)
ans = 1.8124
Pg -22-
Manual de Iniciacin a GNU Octave
-2.8086
1.8124
25.5610
4.6199
1 2 3 4 5 6 7 8 9 10
Pg -23-
Manual de Iniciacin a GNU Octave
En cierta forma se podra decir que el operador (:) representa un rango: en este
caso, los nmeros enteros entre el 1 y el 10. Por defecto el incremento es 1, pero este
operador puede tambin utilizarse con otros valores enteros y reales, positivos o
negativos. En este caso el incremento va entre el valor inferior y el superior, pero
podemos hacer que el incremento sea negativo, o que se haga con un incremento mayor
o menor:
octave:142> x=10:-1:1
x =
10 9 8 7 6 5 4 3 2 1
Pg -24-
Manual de Iniciacin a GNU Octave
Pg -25-
Manual de Iniciacin a GNU Octave
Pg -26-
Manual de Iniciacin a GNU Octave
function y=prueba(x)
y=x+3;
endfunction
Podemos ver que esta funcin es solamente la funcin de una recta, cuya
pendiente es de 45 y desplazada 3 unidades.
y : es el valor de retorno.
prueba : es el nombre de la funcin.
x : es el argumento de entrada.
Una caracterstica de GNU OCTAVE es que las funciones que no tienen
argumentos no llevan parntesis, por lo que a simple vista no siempre son fciles de
distinguir de las simples variables. Ejemplo:
#! hello -qf
printf("hello, world \n")
Pg -27-
Manual de Iniciacin a GNU Octave
octave:1> hello
hello, word
Los nombres de las funciones de GNU Octave no son palabras reservadas del
lenguaje. Es posible crear una variable llamada sin o cos, que ocultan las funciones
correspondientes. Para poder acceder a las funciones hay que eliminar (clear) las
variables del mismo nombre que las ocultan.
Podemos encontrar gran variedad de tipos de funcin segn lo que resuelvan:
1.- Funciones matemticas elementales.
2.- Funciones especiales.
3.- Funciones matriciales elementales.
4.- Funciones matriciales especficas.
5.- Funciones para la descomposicin y/o factorizacin de matrices.
6.- Funciones para anlisis estadstico de datos.
7.- Funciones para anlisis de polinomios.
8.- Funciones para integracin de ecuaciones diferenciales ordinarias.
9.- Resolucin de ecuaciones no-lineales y optimizacin.
10.- Integracin numrica.
11.- Funciones para procesamiento de seal.
-0.85065 0.52573
0.52573 0.85065
Pg -28-
Manual de Iniciacin a GNU Octave
valor_propio =
-0.23607 0.00000
0.00000 4.23607
la funcin eig() calcula los valores y vectores propios de la matriz cuadrada A. Los
vectores propios se devuelven como columnas de la matriz vector_propio, mientras
que los valores propios son los elementos de la matriz diagonal valor_propio.
o Las operaciones de suma y/o resta de una matriz con un escalar consisten en
sumar y/o restar el escalar a todos los elementos de la matriz.
o Recurdese que tecleando help nombre_funcion se obtiene de inmediato
informacin sobre la funcin de ese nombre.
Pg -29-
Manual de Iniciacin a GNU Octave
Pg -30-
Manual de Iniciacin a GNU Octave
1 - 1i 1 - 2i
2 - 3i 2 - 1i
1 + 1i 1 + 2i
2 + 3i 2 + 1i
1 -4 5 -2
Pg -31-
Manual de Iniciacin a GNU Octave
Pg -32-
Manual de Iniciacin a GNU Octave
U =
Pg -33-
Manual de Iniciacin a GNU Octave
2.00000 2.00000
0.50000 0.00000
Pg -34-
Manual de Iniciacin a GNU Octave
octave:54> r
r =
Pg -35-
Manual de Iniciacin a GNU Octave
o Q = orth(A) las columnas de Q son una base ortonormal del espacio vectorial de
las columnas de A, y el nmero de columnas de Q es el rango de A .
octave:62> q=orth(a)
q =
0.36060 0.93272
0.93272 -0.36060
0.100000 0.200000
0.100000 0.200000
octave:68> norm(x,2)
ans = 1.5018
Pg -36-
Manual de Iniciacin a GNU Octave
octave:67> x=rand(1,4)
x =
octave:68> norm(x,2)
ans = 1.5018
octave:69> norm(x,3)
ans = 1.2072
Pg -37-
Manual de Iniciacin a GNU Octave
Cuando alguno de los operadores relacionales vistos previamente (<, >, <=, >=,
== y =) acta entre dos matrices (vectores) del mismo tamao, el resultado es otra
matriz (vector) de ese mismo tamao conteniendo unos y ceros, segn los resultados de
cada comparacin entre elementos hayan sido true o false, respectivamente.
De ordinario, las matrices "binarias" que se obtienen de la aplicacin de los
operadores relacionales no se almacenan en memoria ni se asignan a variables, sino que
se procesan sobre la marcha. GNU OCTAVE dispone de varias funciones para ello.
Recurdese que cualquier valor distinto de cero equivale a true, mientras que un valor
cero equivale a false. Algunas de estas funciones son:
any(x) funcin vectorial; chequea si alguno de los elementos del vector x
cumple una determinada condicin (en este caso ser distinto de cero). Devuelve
un uno un cero
octave:70> any(x)
ans = 1
1 1
Pg -38-
Manual de Iniciacin a GNU Octave
1 1
1 2 3 4
find(A) cuando esta funcin se aplica a una matriz la considera como un vector
con una columna detrs de otra, de la 1 a la ltima.
Pg -39-
Manual de Iniciacin a GNU Octave
1 2 3 4 NaN 6
octave:90> isnan(x)
ans =
0 0 0 0 1 0
isinf() chequea si hay valores Inf, devolviendo una matriz de unos y ceros
octave:91> isinf(x)
ans =
0 0 0 0 0 0
1 1 1 1 0 1
Pg -40-
Manual de Iniciacin a GNU Octave
Pg -41-
Manual de Iniciacin a GNU Octave
Pg -42-
Manual de Iniciacin a GNU Octave
octave:3> c=char('mas','madera')
c =
mas
madera
octave:7> char(112)
ans = p
octave:8> char(121)
ans = y
octave:9> char(23)
ans = _
octave:10> double(b)
ans =
11 112 121 23
1 12
1 8
Pg -43-
Manual de Iniciacin a GNU Octave
octave:15> strcmp(a,b)
ans = 0
octave:16> strcmp(b,b)
ans = 1
octave:17> a='en un lugar de la mancha de cuyo nombre no puedo
acordarme'
a = en un lugar de la mancha de cuyo nombre no puedo acordarme
octave:18> b='n';
octave:19> findstr(a,b)
ans =
2 5 21 34 41
octave:20> strmatch(a,b)
ans = [](0x0)
octave:21> strrep(a,b,'T')
ans = eT uT lugar de la maTcha de cuyo Tombre To puedo acordarme
Pg -44-
Manual de Iniciacin a GNU Octave
octave:25> rand(2,2,2)
ans =
ans(:,:,1) =
0.31106 0.70197
0.48694 0.45170
ans(:,:,2) =
0.017063 0.261818
0.234682 0.340703
Pg -45-
Manual de Iniciacin a GNU Octave
2.3. Estructuras
Una estructura (struct) es una agrupacin de datos de tipo diferente bajo un
mismo nombre. Estos datos se llaman miembros (members) o campos (fields). Una
estructura es un nuevo tipo de dato, del que luego se pueden crear muchas variables
(objetos o instances). Por ejemplo, la estructura alumno puede contener los campos
nombre (una cadena de caracteres) y carnet (un nmero).
Pg -46-
Manual de Iniciacin a GNU Octave
octave:39> alumno.edad=23
alumno =
{
dni = 77334059
edad = 23
nombre = jose maria
}
Como hemos visto desde un inicio, GNU Octave trabaja con matrices, por lo tanto, todo
lo que veamos para un elemento es extrapolable a una matriz, vector o conjunto de
estos, por lo tanto, podemos hacer matrices de structs al igual que hemos hecho structs
de vectores/matrices.
Pg -47-
Manual de Iniciacin a GNU Octave
{
[1,1] =
1 1 2
{
[1,1] =
1 1 2
Pg -48-
Manual de Iniciacin a GNU Octave
octave:44> vc(3)={rand(2,2)}
vc =
{
[1,1] =
1 1 2
0.39113 0.97938
0.41501 0.77790
}
Otra nomenclatura alternativa y similar, que tambin utiliza llaves, es la que
podemos ver a continuacin.
octave:45> v{1}=[1 2 1]
v =
{
[1,1] =
1 2 1
Pg -49-
Manual de Iniciacin a GNU Octave
octave:46> v{2}='escriche'
v =
{
[1,1] =
1 2 1
[1,2] = escriche
}
octave:48> c=cell(2,2)
c =
{
[1,1] = [](0x0)
[2,1] = [](0x0)
[1,2] = [](0x0)
[2,2] = [](0x0)
}
Pg -50-
Manual de Iniciacin a GNU Octave
{
[1,1] = jose maria
[2,1] = [](0x0)
[1,2] = [](0x0)
[2,2] = [](0x0)
}
octave:50> c{2,2}='azucar'
c =
{
[1,1] = jose maria
[2,1] = [](0x0)
[1,2] = [](0x0)
[2,2] = azucar
}
Pg -51-
Manual de Iniciacin a GNU Octave
Los bucles nos permiten realizar varias iteraciones de un mismo proceso, o sea, realizar
una misma operacin sobre distintos elementos. Podemos encontrar varios tipos de
bucles:
while
do-until
for
Adems de las sentencias break y continue utilizadas dentro de los bucles para salir del
proceso.
Pg -52-
Manual de Iniciacin a GNU Octave
3.1.1. Sentencia IF
Esta sentencia nos sirve para hacer bifurcaciones, podemos hacer 3 usos diferentes de
ella:
Una sola sentencia que utilizamos si es verdadera y sino no hacemos nada:
if (condition)
then-body
endif
Pg -53-
Manual de Iniciacin a GNU Octave
Una observacin muy importante: la condicin del if puede ser una condicin
matricial, del tipo A==B, donde A y B son matrices del mismo tamao. Para que se
considere que la condicin se cumple, es necesario que sean iguales dos a dos todos los
elementos de las matrices A y B. Basta que haya dos elementos diferentes para que las
matrices no sean iguales, y por tanto las sentencias del if no se ejecuten. Anlogamente,
una condicin en la forma A=B exige que todos los elementos sean diferentes dos a
dos. Bastara que hubiera dos elementos iguales para que la condicin no se cumpliese.
En resumen:
if A==B exige que todos los elementos sean iguales dos a dos
if A=B exige que todos los elementos sean diferentes dos a dos
Se trata de una sentencia con la que podemos hacer una funcin similar a la
concatenacin de sentencias elseif, de manera que simplifiquemos el modo de
programar:
switch expression
case label
command_list
case label
command_list
...
otherwise
#con este ltimo agregamos todas las posibilidades que no se
#contemplan en los anteriores
command_list
endswitch
Pg -54-
Manual de Iniciacin a GNU Octave
Repite una serie de sentencias un nmero determinado de veces, sin importar los
procesos que ocurran dentro, por lo que la nica manera de salir del bucle es esperar que
acabe (ms adelante veremos la sentencia break).
Repite una serie de sentencias hasta que la condicin until se hace true,
momento en el que se detiene la ejecucin.
do
body
until (condition)
while (condition)
body
endwhile
Pg -55-
Manual de Iniciacin a GNU Octave
Pg -56-
Manual de Iniciacin a GNU Octave
Los ficheros de comandos o scripts son ficheros con un nombre tal como file1.m
que contienen una sucesin de comandos anloga a la que se tecleara en el uso
interactivo del programa. Dichos comandos se ejecutan sucesivamente cuando se teclea
el nombre del fichero que los contiene (sin la extensin), es decir cuando se teclea file1
con el ejemplo considerado.
Cuando se ejecuta desde la lnea de comandos, las variables creadas por file1
pertenecen al espacio de trabajo base de GNU OCTAVE. Por el contrario, si se ejecuta
desde una funcin, las variables que crea pertenecen al espacio de trabajo de la funcin.
En los ficheros de comandos conviene poner los puntos y coma (;) al final de
cada sentencia, para evitar una salida de resultados demasiado cuantiosa. Un fichero
*.m puede llamar a otros ficheros *.m, e incluso se puede llamar a s mismo de modo
recursivo.
El comando echo hace que se impriman los comandos que estn en un script a
medida que van siendo ejecutados. Este comando tiene varias formas:
echo on activa el echo en todos los ficheros script
echo off desactiva el echo
echo file on donde 'file' es el nombre de un fichero de funcin, activa el echo en
esa funcin
echo file off desactiva el echo en la funcin
echo file pasa de on a off y viceversa
echo on all activa el echo en todas las funciones
echo off all desactiva el echo de todas las funciones
Mencin especial merece el fichero de comandos octaverc. Este fichero se
ejecuta cada vez que se entra en GNU OCTAVE. En l puede introducir todos aquellos
comandos que le interesa se ejecuten siempre al iniciar la sesin, por ejemplo format
compact y los comandos necesarios para modificar el path.
Pg -57-
Manual de Iniciacin a GNU Octave
La primera lnea de un fichero llamado name.m que define una funcin tiene la forma:
Pg -58-
Manual de Iniciacin a GNU Octave
Tambin las funciones creadas por el usuario pueden tener su help, anlogo al
que tienen las propias funciones de GNU OCTAVE. Esto se consigue de la siguiente
forma: las primeras lneas de comentarios de cada fichero de funcin son muy
importantes, pues permiten construir un help sobre esa funcin.
En otras palabras, cuando se teclea en la ventana de comandos de GNU
OCTAVE:
help mi_func
el programa responde escribiendo las primeras lneas del fichero mi_func.m que
comienzan por el carcter #, es decir, que son comentarios.
Pg -59-
Manual de Iniciacin a GNU Octave
4. Grficos bidimensionales
A estas alturas, despus de ver cmo funciona este programa, a nadie le puede
resultar extrao que los grficos 2-D de GNU Octave estn fundamentalmente
orientados a la representacin grfica de vectores (y matrices). En el caso ms sencillo
los argumentos bsicos de la funcin plot van a ser vectores. Cuando una matriz
aparezca como argumento, se considerar como un conjunto de vectores columna (en
algunos casos tambin de vectores fila).
GNU Octave utiliza un tipo especial de ventanas para realizar las operaciones
grficas. Ciertos comandos abren una ventana nueva y otros dibujan sobre la ventana
activa, bien sustituyendo lo que hubiera en ella, bien aadiendo nuevos elementos
grficos a un dibujo anterior. Todo esto se ver con ms detalle en las siguientes
secciones.
Todo este sistema de grficos est implementado a partir de GNU Plot, por lo
que si fuera necesario, siempre podramos llamar directamente a este programa en vez
de dejar que sea Octave el que lo haga por nosotros.
Pg -60-
Manual de Iniciacin a GNU Octave
Existen adems otras funciones orientadas a aadir ttulos al grfico, a cada uno
de los ejes, a dibujar una cuadrcula auxiliar, a introducir texto, etc. Estas funciones son
las siguientes:
title('ttulo') aade un ttulo al dibujo.
xlabel('tal') aade una etiqueta al eje de abscisas. Con xlabel off
desaparece.
ylabel('cual') aade una etiqueta al eje de ordenadas. Con ylabel off
desaparece.
text(x,y,'texto') introduce 'texto' en el lugar especificado por las
coordenadas x e y. Si x e y son vectores, el texto se
repite por cada par de elementos. Si texto es tambin un
vector de cadenas de texto de la misma dimensin, cada
elemento se escribe en las coordenadas
correspondientes.
legend() define rtulos para las distintas lneas o ejes utilizados en
la figura. Para ms detalle, consultar el Help.
grid activa la inclusin de una cuadrcula en el dibujo. Con
grid off desaparece la cuadrcula.
Pg -61-
Manual de Iniciacin a GNU Octave
Ms adelante se ver que con la funcin hold pueden aadirse grficos a una
figura ya existente respetando su contenido.
Pg -62-
Manual de Iniciacin a GNU Octave
1 3 2 4 5 3
El resultado de este comando es que se abre una ventana. Por defecto, los
distintos puntos del grfico se unen con una lnea continua. Tambin por defecto, el
color que se utiliza para la primera lnea es el rojo.
Cuando a la funcin plot() se le pasa un nico vector real como argumento,
dicha funcin dibuja en ordenadas el valor de los n elementos del vector frente a los
ndices 1, 2, ... n del mismo en abscisas. Ms adelante se ver que si el vector es
complejo, el funcionamiento es bastante diferente.
Pg -63-
Manual de Iniciacin a GNU Octave
Pg -64-
Manual de Iniciacin a GNU Octave
Pg -65-
Manual de Iniciacin a GNU Octave
y yellow . puntos
m magenta o crculos
c cyan x marcas en x
r r ed + marcas en +
g green * marcas en *
b blue s marcas
cuadradas (square)
w white d marcas en
diamante (diamond)
k black ^ tringulo
apuntando arriba
Pg -66-
Manual de Iniciacin a GNU Octave
Pg -67-
Manual de Iniciacin a GNU Octave
mientras que :
axis(auto)
Pg -68-
Manual de Iniciacin a GNU Octave
Pg -69-
Manual de Iniciacin a GNU Octave
Pg -70-
Manual de Iniciacin a GNU Octave
Pg -71-
Manual de Iniciacin a GNU Octave
5. Grficos tridimensionales
Quizs sea sta una de las caractersticas de GNU OCTAVE que ms
admiracin despierta entre los usuarios no tcnicos (cualquier alumno de ingeniera sabe
que hay ciertas operaciones algebraicas como la descomposicin de valor singular, sin ir
ms lejos, que tienen dificultades muy superiores, aunque "luzcan" menos).
GNU Octave tiene posibilidades de realizar varios tipos de grficos 3D. Para
darse una idea de ello, lo mejor es verlo en la pantalla cuanto antes, aunque haya que
dejar las explicaciones detalladas para un poco ms adelante.
La primera forma de grfico 3D es la funcin plot3, que es el anlogo
tridimensional de la funcin plot. Esta funcin dibuja puntos cuyas coordenadas estn
contenidas en 3 vectores, bien unindolos mediante una lnea continua (defecto), bien
mediante markers.
Asegrese de que no hay ninguna ventana grfica abierta y ejecute el siguiente
comando que dibuja una lnea espiral:
octave:1> fi=[0:pi/20:6*pi]; plot3(cos(fi),sin(fi),fi,'g')
Ahora se ver cmo se representa una funcin de dos variables. Para ello se
va a definir una funcin de este tipo en un fichero llamado test3d.m. La frmula ser la
siguiente:
Pg -72-
Manual de Iniciacin a GNU Octave
function z=test3d(x,y)
z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...
- 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...
1/3*exp(-(x+1).^2 y.^2);
Pg -73-
Manual de Iniciacin a GNU Octave
Pg -74-
Manual de Iniciacin a GNU Octave
closeplot
u=-8:0.5:8; v=u;
[U,V]=meshgrid(u,v);
R=sqrt(U.^2+V.^2)+eps;
Pg -75-
Manual de Iniciacin a GNU Octave
W=sin(R)./R;
mesh(W)
Pg -76-
Manual de Iniciacin a GNU Octave
Pg -77-
Manual de Iniciacin a GNU Octave
view(azimut, elev)
view([xd,yd,zd])
axis([xmin,xmax,ymin,ymax,zmin,zmax])
Pg -78-
Manual de Iniciacin a GNU Octave
octave:2>save
octave:3>load
octave:4>save filename A, x, y
octave:5>load filename
Pg -79-
Manual de Iniciacin a GNU Octave
Pg -80-
Manual de Iniciacin a GNU Octave
octave:32>diary filename
Pg -81-
Manual de Iniciacin a GNU Octave
function y=prueba(x)
y = 1./((x-.3).^2+.01)+1./((x-.9).^2+.04)-6;
octave:45>area = quad('prueba', 0, 1)
area =
29.8583
Pg -82-
Manual de Iniciacin a GNU Octave
function deriv=tiropar(t,y)
fac=-(0.001/1.0)*sqrt((y(1)^2+y(2)^2));
deriv=zeros(4,1);
deriv(1)=fac*y(1);
deriv(2)=fac*y(2)-9.8;
deriv(3)=y(1);
deriv(4)=y(2);
end
donde se han supuesto unas constantes con los valores de c=0.001, m=1 y g=9.8.
Falta fijar los valores iniciales de posicin y velocidad. Se supondr que el proyectil
parte del origen con una velocidad de 100 m/seg y con un ngulo de 30, lo que conduce
a los valores iniciales siguientes:
u(0)=100*cos(pi/6), v(0)=100*sin(pi/6), x(0)=0, y(0)=0.
Los comandos para realizar la integracin son los siguientes (se podran agrupar en un
fichero llamado tiroparMain.m):
t0=0;
tf=9;
y0=[100*cos(pi/6) 100*sin(pi/6) 0 0]';
[t,Y]=ode23('tiropar',[t0,tf],y0);
plot(t,Y(:,4)) # dibujo de la altura en funcion del tiempo
podemos encontrar varios tipos de funciones que resuelven ecuaciones
diferenciales:
ode23 : resuelve ecuaciones diferenciales de 2 y 3er orden
ode45 : resuelve ecuaciones diferenciales de 4 y 5 orden
ode78 : resuelve ecuaciones diferenciales usando frmulas de 7 orden
Pg -83-
GNUFreeDocumentationLicense
GNUFreeDocumentationLicense
Version1.2,November2002
Copyright(C)2000,2001,2002FreeSoftwareFoundation,Inc.
51FranklinSt,FifthFloor,Boston,MA021101301USA
Everyoneispermittedtocopyanddistributeverbatimcopies
ofthislicensedocument,butchangingitisnotallowed.
0.PREAMBLE
ThepurposeofthisLicenseistomakeamanual,textbook,orotherfunctionalandusefuldocument
"free"inthesenseoffreedom:toassureeveryonetheeffectivefreedomtocopyandredistributeit,
withorwithoutmodifyingit,eithercommerciallyornoncommercially.
Secondarily,thisLicensepreservesfortheauthorandpublisherawaytogetcreditfortheirwork,
whilenotbeingconsideredresponsibleformodificationsmadebyothers.
ThisLicenseisakindof"copyleft",whichmeansthatderivativeworksofthedocumentmust
themselvesbefreeinthesamesense.ItcomplementstheGNUGeneralPublicLicense,whichisa
copyleftlicensedesignedforfreesoftware.
WehavedesignedthisLicenseinordertouseitformanualsforfreesoftware,becausefreesoftware
needsfreedocumentation:afreeprogramshouldcomewithmanualsprovidingthesamefreedoms
thatthesoftwaredoes.ButthisLicenseisnotlimitedtosoftwaremanuals;itcanbeusedforany
textual work, regardless of subject matter or whether it is published as a printed book. We
recommendthisLicenseprincipallyforworkswhosepurposeisinstructionorreference.
1.APPLICABILITYANDDEFINITIONS
ThisLicenseappliestoanymanualorotherwork,inanymedium,thatcontainsanoticeplacedby
thecopyrightholdersayingitcanbedistributedunderthetermsofthisLicense. Suchanotice
grants a worldwide, royaltyfree license, unlimited in duration, to use that work under the
conditionsstatedherein.The"Document",below,referstoanysuchmanualorwork.Anymember
ofthepublicisalicensee,andisaddressedas"you".Youacceptthelicenseifyoucopy,modifyor
distributetheworkinawayrequiringpermissionundercopyrightlaw.
A"ModifiedVersion"oftheDocumentmeansanyworkcontainingtheDocumentoraportionofit,
eithercopiedverbatim,orwithmodificationsand/ortranslatedintoanotherlanguage.
A"SecondarySection"isanamedappendixorafrontmattersectionoftheDocumentthatdeals
exclusivelywiththerelationshipofthepublishersorauthorsoftheDocumenttotheDocument's
overallsubject(ortorelatedmatters)andcontainsnothingthatcouldfalldirectlywithinthatoverall
subject.(Thus,iftheDocumentisinpartatextbookofmathematics,aSecondarySectionmaynot
explainanymathematics.) Therelationshipcouldbeamatterofhistoricalconnectionwiththe
subjectorwithrelatedmatters,oroflegal,commercial,philosophical,ethicalorpoliticalposition
regardingthem.
The"InvariantSections"arecertainSecondarySectionswhosetitlesaredesignated,asbeingthose
ofInvariantSections,inthenoticethatsaysthattheDocumentisreleasedunderthisLicense.Ifa
sectiondoesnotfittheabovedefinitionofSecondarythenitisnotallowedtobedesignatedas
Invariant.TheDocumentmaycontainzeroInvariantSections.IftheDocumentdoesnotidentify
anyInvariantSectionsthentherearenone.
The"CoverTexts"arecertainshortpassagesoftextthatarelisted,asFrontCoverTextsorBack
CoverTexts,inthenoticethatsaysthattheDocumentisreleasedunderthisLicense.AFrontCover
Textmaybeatmost5words,andaBackCoverTextmaybeatmost25words.
A"Transparent"copyoftheDocumentmeansamachinereadablecopy,representedinaformat
whosespecificationisavailabletothegeneralpublic,thatissuitableforrevisingthedocument
straightforwardly with generic text editors or (for images composed of pixels) generic paint
programsor(fordrawings)somewidelyavailabledrawingeditor,andthatissuitableforinputto
text formatters or for automatic translation to a variety of formats suitable for input to text
formatters. AcopymadeinanotherwiseTransparentfileformatwhosemarkup,orabsenceof
markup, has been arranged to thwart or discourage subsequent modification by readers is not
Transparent.AnimageformatisnotTransparentifusedforanysubstantialamountoftext.Acopy
thatisnot"Transparent"iscalled"Opaque".
ExamplesofsuitableformatsforTransparentcopiesincludeplainASCIIwithoutmarkup,Texinfo
inputformat,LaTeXinputformat,SGMLorXMLusingapubliclyavailableDTD,andstandard
conforming simple HTML, PostScript or PDF designed for humanmodification. Examples of
transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary
formatsthatcanbereadandeditedonlybyproprietarywordprocessors,SGMLorXMLforwhich
theDTDand/orprocessingtoolsarenotgenerallyavailable,andthemachinegeneratedHTML,
PostScriptorPDFproducedbysomewordprocessorsforoutputpurposesonly.
The"TitlePage"means,foraprintedbook,thetitlepageitself,plussuchfollowingpagesasare
neededtohold,legibly,thematerialthisLicenserequirestoappearinthetitlepage.Forworksin
formats which do not have any title page as such, "Title Page" means the text near the most
prominentappearanceofthework'stitle,precedingthebeginningofthebodyofthetext.
Asection"EntitledXYZ"meansanamedsubunitoftheDocumentwhosetitleeitherisprecisely
XYZorcontainsXYZinparenthesesfollowingtextthattranslatesXYZinanotherlanguage.(Here
XYZ stands for a specific section name mentioned below, such as "Acknowledgements",
"Dedications","Endorsements",or"History".)To"PreservetheTitle"ofsuchasectionwhenyou
modifytheDocumentmeansthatitremainsasection"EntitledXYZ"accordingtothisdefinition.
TheDocumentmayincludeWarrantyDisclaimersnexttothenoticewhichstatesthatthisLicense
appliestotheDocument.TheseWarrantyDisclaimersareconsideredtobeincludedbyreferencein
thisLicense,butonlyasregardsdisclaimingwarranties:anyotherimplicationthattheseWarranty
DisclaimersmayhaveisvoidandhasnoeffectonthemeaningofthisLicense.
2.VERBATIMCOPYING
You may copy and distribute the Document in any medium, either commercially or
noncommercially,providedthatthisLicense,thecopyrightnotices,andthelicensenoticesaying
this License applies to the Document are reproduced in all copies, and that you add no other
conditionswhatsoevertothoseofthisLicense.Youmaynotusetechnicalmeasurestoobstructor
controlthereadingorfurthercopyingofthecopiesyoumakeordistribute. However,youmay
acceptcompensationinexchangeforcopies.Ifyoudistributealargeenoughnumberofcopiesyou
mustalsofollowtheconditionsinsection3.
Youmayalsolendcopies,underthesameconditionsstatedabove,andyoumaypubliclydisplay
copies.
3.COPYINGINQUANTITY
If you publish printed copies (or copies in media that commonly have printed covers) of the
Document,numberingmorethan100,andtheDocument'slicensenoticerequiresCoverTexts,you
mustenclosethecopiesincoversthatcarry,clearlyandlegibly,alltheseCoverTexts:FrontCover
Textsonthefrontcover,andBackCoverTextsonthebackcover.Bothcoversmustalsoclearlyand
legiblyidentifyyouasthepublisherofthesecopies.Thefrontcovermustpresentthefulltitlewith
allwordsofthetitleequallyprominentandvisible.Youmayaddothermaterialonthecoversin
addition. Copyingwithchanges limited tothecovers,as longas theypreservethe titleof the
Documentandsatisfytheseconditions,canbetreatedasverbatimcopyinginotherrespects.
Iftherequiredtextsforeithercoveraretoovoluminoustofitlegibly,youshouldputthefirstones
listed(asmanyasfitreasonably)ontheactualcover,andcontinuetherestontoadjacentpages.
IfyoupublishordistributeOpaquecopiesoftheDocumentnumberingmorethan100,youmust
eitherincludeamachinereadableTransparentcopyalongwitheachOpaquecopy,orstateinor
witheachOpaquecopyacomputernetworklocationfromwhichthegeneralnetworkusingpublic
hasaccesstodownloadusingpublicstandardnetworkprotocolsacompleteTransparentcopyofthe
Document,freeofaddedmaterial.Ifyouusethelatteroption,youmusttakereasonablyprudent
steps,whenyoubegindistributionofOpaquecopiesinquantity,toensurethatthisTransparentcopy
willremainthusaccessibleatthestatedlocationuntilatleastoneyearafterthelasttimeyou
distributeanOpaquecopy(directlyorthroughyouragentsorretailers)ofthateditiontothepublic.
It is requested, but not required, that you contact the authors of the Document well before
redistributinganylargenumberofcopies,togivethemachancetoprovideyouwithanupdated
versionoftheDocument.
4.MODIFICATIONS
YoumaycopyanddistributeaModifiedVersionoftheDocumentundertheconditionsofsections
2and3above,providedthatyoureleasetheModifiedVersionunderpreciselythisLicense,withthe
ModifiedVersionfillingtheroleoftheDocument,thuslicensingdistributionandmodificationof
theModifiedVersiontowhoeverpossessesacopyofit.Inaddition,youmustdothesethingsinthe
ModifiedVersion:
A.UseintheTitlePage(andonthecovers,ifany)atitledistinctfromthatoftheDocument,and
fromthoseofpreviousversions(whichshould,iftherewereany,belistedintheHistorysection
oftheDocument).Youmayusethesametitleasapreviousversioniftheoriginalpublisherofthat
versiongivespermission.
B.ListontheTitlePage,asauthors,oneormorepersonsorentitiesresponsibleforauthorshipof
themodificationsintheModifiedVersion,togetherwithatleastfiveoftheprincipalauthorsofthe
Document(allofitsprincipalauthors,ifithasfewerthanfive),unlesstheyreleaseyoufromthis
requirement.
C.StateontheTitlepagethenameofthepublisheroftheModifiedVersion,asthepublisher.
D.PreserveallthecopyrightnoticesoftheDocument.
E. Add an appropriate copyright notice for your modifications adjacent to the other copyright
notices.
F.Include,immediatelyafterthecopyrightnotices,alicensenoticegivingthepublicpermissionto
usetheModifiedVersionunderthetermsofthisLicense,intheformshownintheAddendum
below.
G.PreserveinthatlicensenoticethefulllistsofInvariantSectionsandrequiredCoverTextsgiven
intheDocument'slicensenotice.
H.IncludeanunalteredcopyofthisLicense.
I.PreservethesectionEntitled"History",PreserveitsTitle,andaddtoitanitemstatingatleastthe
title,year,newauthors,andpublisheroftheModifiedVersionasgivenontheTitlePage.Ifthereis
no section Entitled "History" in the Document, create one stating the title, year, authors, and
publisheroftheDocumentasgivenonitsTitlePage,thenaddanitemdescribingtheModified
Versionasstatedintheprevioussentence.
J.Preservethenetworklocation,ifany,givenintheDocumentforpublicaccesstoaTransparent
copyoftheDocument,andlikewisethenetworklocationsgivenintheDocumentforprevious
versionsitwasbasedon.Thesemaybeplacedinthe"History"section.Youmayomitanetwork
locationforaworkthatwaspublishedatleastfouryearsbeforetheDocumentitself,orifthe
originalpublisheroftheversionitreferstogivespermission.
K.ForanysectionEntitled"Acknowledgements"or"Dedications",PreservetheTitleofthesection,
andpreserveinthesectionallthesubstanceandtoneofeachofthecontributoracknowledgements
and/ordedicationsgiventherein.
L.PreservealltheInvariantSectionsoftheDocument,unalteredintheirtextandintheirtitles.
Sectionnumbersortheequivalentarenotconsideredpartofthesectiontitles.
M. Delete any section Entitled "Endorsements". Such a section may not be included in the
ModifiedVersion.
N.DonotretitleanyexistingsectiontobeEntitled"Endorsements"ortoconflictintitlewithany
InvariantSection.
O.PreserveanyWarrantyDisclaimers.
IftheModifiedVersionincludesnewfrontmattersectionsorappendicesthatqualifyasSecondary
SectionsandcontainnomaterialcopiedfromtheDocument,youmayatyouroptiondesignate
someorallofthesesectionsasinvariant.Todothis,addtheirtitlestothelistofInvariantSections
intheModifiedVersion'slicensenotice.Thesetitlesmustbedistinctfromanyothersectiontitles.
YoumayaddasectionEntitled"Endorsements",provideditcontainsnothingbutendorsementsof
yourModifiedVersionbyvariouspartiesforexample,statementsofpeerrevieworthatthetexthas
beenapprovedbyanorganizationastheauthoritativedefinitionofastandard.
YoumayaddapassageofuptofivewordsasaFrontCoverText,andapassageofupto25words
asaBackCoverText,totheendofthelistofCoverTextsintheModifiedVersion. Onlyone
passageofFrontCoverTextandoneofBackCoverTextmaybeaddedby(orthrougharrangements
made by) any one entity. If the Document already includes a cover text for the same cover,
previouslyaddedbyyouorbyarrangementmadebythesameentityyouareactingonbehalfof,you
maynotaddanother;butyoumayreplacetheoldone,onexplicitpermissionfromtheprevious
publisherthataddedtheoldone.
Theauthor(s)andpublisher(s)oftheDocumentdonotbythisLicensegivepermissiontousetheir
namesforpublicityforortoassertorimplyendorsementofanyModifiedVersion.
5.COMBININGDOCUMENTS
YoumaycombinetheDocumentwithotherdocumentsreleasedunderthisLicense,undertheterms
definedinsection4aboveformodifiedversions,providedthatyouincludeinthecombinationallof
theInvariantSectionsofalloftheoriginaldocuments,unmodified,andlistthemallasInvariant
Sections of your combinedworkinits licensenotice,andthatyoupreservealltheirWarranty
Disclaimers.
ThecombinedworkneedonlycontainonecopyofthisLicense,andmultipleidenticalInvariant
Sectionsmaybereplacedwithasinglecopy.IftherearemultipleInvariantSectionswiththesame
namebutdifferentcontents,makethetitleofeachsuchsectionuniquebyaddingattheendofit,in
parentheses,thenameoftheoriginalauthororpublisherofthatsectionifknown,orelseaunique
number.MakethesameadjustmenttothesectiontitlesinthelistofInvariantSectionsinthelicense
noticeofthecombinedwork.
In the combination, you must combine any sections Entitled "History" in the various original
documents, forming one section Entitled "History"; likewise combine any sections Entitled
"Acknowledgements", and any sections Entitled "Dedications". You must delete all sections
Entitled"Endorsements".
6.COLLECTIONSOFDOCUMENTS
YoumaymakeacollectionconsistingoftheDocumentandotherdocumentsreleasedunderthis
License,andreplacetheindividualcopiesofthisLicenseinthevariousdocumentswithasingle
copy that is included in the collection, provided that you follow the rules of this License for
verbatimcopyingofeachofthedocumentsinallotherrespects.
Youmayextractasingledocumentfromsuchacollection,anddistributeitindividuallyunderthis
License,providedyouinsertacopyofthisLicenseintotheextracteddocument,andfollowthis
Licenseinallotherrespectsregardingverbatimcopyingofthatdocument.
7.AGGREGATIONWITHINDEPENDENTWORKS
AcompilationoftheDocumentoritsderivativeswithotherseparateandindependentdocumentsor
works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the
copyrightresultingfromthecompilationisnotusedtolimitthelegalrightsofthecompilation's
usersbeyondwhattheindividualworkspermit.WhentheDocumentisincludedinanaggregate,
thisLicensedoesnotapplytotheotherworksintheaggregatewhicharenotthemselvesderivative
worksoftheDocument.
IftheCoverTextrequirementofsection3isapplicabletothesecopiesoftheDocument,thenifthe
Documentislessthanonehalfoftheentireaggregate,theDocument'sCoverTextsmaybeplaced
oncoversthatbrackettheDocumentwithintheaggregate,ortheelectronicequivalentofcoversif
theDocumentisinelectronicform.Otherwisetheymustappearonprintedcoversthatbracketthe
wholeaggregate.
8.TRANSLATION
Translationisconsideredakindofmodification,soyoumaydistributetranslationsoftheDocument
under the terms of section 4. Replacing Invariant Sections with translations requires special
permissionfromtheircopyrightholders,butyoumayincludetranslationsofsomeorallInvariant
Sections in addition to the original versions of these Invariant Sections. You may include a
translation of this License, and all the license notices in the Document, and any Warranty
Disclaimers,providedthatyoualsoincludetheoriginalEnglishversionofthisLicenseandthe
originalversionsofthosenoticesanddisclaimers.Incaseofadisagreementbetweenthetranslation
andtheoriginalversionofthisLicenseoranoticeordisclaimer,theoriginalversionwillprevail.
9.TERMINATION
Youmaynotcopy,modify,sublicense,ordistributetheDocumentexceptasexpresslyprovidedfor
underthisLicense. Anyotherattempttocopy,modify,sublicenseordistributetheDocumentis
void,andwillautomaticallyterminateyourrightsunderthisLicense.However,partieswhohave
receivedcopies,orrights,fromyouunderthisLicensewillnothavetheirlicensesterminatedso
longassuchpartiesremaininfullcompliance.
10.FUTUREREVISIONSOFTHISLICENSE
TheFreeSoftwareFoundationmaypublishnew,revisedversionsoftheGNUFreeDocumentation
Licensefromtimetotime.Suchnewversionswillbesimilarinspirittothepresentversion,but
maydifferindetailtoaddressnewproblemsorconcerns.Seehttp://www.gnu.org/copyleft/.
EachversionoftheLicenseisgivenadistinguishingversionnumber.IftheDocumentspecifiesthat
aparticularnumberedversionofthisLicense"oranylaterversion"appliestoit,youhavetheoption
offollowingthetermsandconditionseitherofthatspecifiedversionorofanylaterversionthathas
beenpublished(notasadraft)bytheFreeSoftwareFoundation.IftheDocumentdoesnotspecify
aversionnumberofthisLicense,youmaychooseanyversioneverpublished(notasadraft)bythe
FreeSoftwareFoundation.