Vous êtes sur la page 1sur 109

Introducción a la

escritura cientı́fica en
LATEX 2ε

David Gómez-Castro

Departamento de Análisis Matemático y Matemática Aplicada


Universidad Complutense de Madrid
dgcastro@ucm.es
https://blogs.mat.ucm.es/dgcastro

Diciembre 2018

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 1 / 80


Desarrollo del curso I
Sesión 1: Bienvenido a LATEX

1 Instalación

2 ¡Hola Mundo! e ingredientes básicos

Sesión 2: LATEX para Matemáticas

3 Fórmulas
Distintos tipos de fórmulas
Sı́mbolos
Matrices
Diagramas

4 Teoremas

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 2 / 80


Desarrollo del curso II
Sesión 3: LATEX como editor de texto avanzado
5 Insertando objetos
Figuras
Tablas
Códigos
6 Formato avanzado
Secciones e ı́ndices
El formato de página
El formato de la Facultad
Sesión 4: Referencias
7 Referencias a elementos del texto
Etiquetas
Referencias básicas de LATEX
El paquete cleveref
8 Referencias a bibliografı́a
David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 3 / 80
Desarrollo del curso III
Sesión 5:

9 Presentaciones en Beamer

Sesión 6:

10 Gráficos avanzados
Dibujo libre
Representación de funciones
Representación de datos

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 4 / 80


Material de apoyo

Url
Google. Si no: lmgtfy.com
TEX Stack Exchange
The not so short introduction to LaTeX2e (actualmente en 139
minutos)

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 5 / 80


Sesión I

Bienvenido a LATEX

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 6 / 80


¿Qué es LATEX?

LATEX es un sistema de preparación de documentos, utilizado en


documentos cientı́ficos y técnicos.

LATEX ¡no es un procesador de textos! Nos permite separar el contenido del


continente, dejando el formato a un lado.

Por eso, LATEX se escribe en documentos de texto “sin formato” con una
cabecera que dice cómo será el formato (tipo de letra, espaciados,
márgenes, tı́tulos...).

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 7 / 80


unique, product ground state.
1
Hamiltonian construction
Δ (H) ≥
We first relate undecidability of the spectral gap to undecidability of

¿Por qué LATEX? 0


0

Figure 1 | Gapped and gapless systems. a, A gapped system has a unique


ground state λ0(H) and a constant lower-bound γ on the spectral gap
another important physical quantity, the ground state energy density,
which, for a 2D lattice, is given by Eρ = lim [λ 0 (HL )/L2] . We then
L →∞
∆(H) = λ1 −λ0 in the thermodynamic limit. b, A gapless system has transform the halting problem into a question about ground state
continuous spectrum λi(H) above the ground state in the thermodynamic energy densities.
limit. Reducing the ground state energy density problem to the spectral
gap problem requires two ingredients.
¿Quién lo usa? ∆(HL) ≥ γ > 0 for all sufficiently large L. We take ‘gapless’ to mean (1) It requires a translationally invariant Hamiltonian Hu(ϕ) on a 2D
the system has continuous spectrum above the ground state in the square lattice with local interactions hu(ϕ), whose ground state energy
thermodynamic limit. density is either strictly positive or tends to zero from below in the
Here gapped is not the negation of gapless; there are systems that thermodynamic limit, depending on the value of an external parame-
fall into neither category. We adopt such strong definitions to delib- ter ϕ; however, determining which case holds should be undecidable.

ARTICLE
erately exclude ambiguous cases, such as systems with degenerate Constructing such a Hamiltonian constitutes the main technical work
ground states. A Hamiltonian that is gapped or gapless according to of our result. (These properties of Hu(ϕ) are unaffected if we multiply
the above definitions is recognized as such throughout the literature. hu(ϕ) by an arbitrary fixed rational number β, no matter how small.)
We show that the spectral gap problem is undecidable even given that (2) It requires a gapless Hamiltonian Hd with translationally invariant
1 Las principales the Hamiltonian either has a unique ground state and a spectral gap of local interactions hd and a ground state energy of zero. (Recall that by
magnitude one, or has continuous spectrum above the ground state. ‘gapless’ we mean continuous spectrum above the ground state, not
doi:10.1038/nature16059

We prove this by showing that the halting problem for Turing merely a vanishing spectral gap.) There are many well-known examples
revistas del
Undecidability of the spectral gap
machines can be encoded in the spectral gap problem, implying that of such Hamiltonians, for example, that associated with the critical
the latter is at least as hard as the former. A Turing machine is a simple, XY model1.
abstract model of computation in which a head reads and writes sym- Given Hamiltonians with these properties, we construct a new trans-
mundo: Nature, bols
Toby from some finite
S. Cubitt 1,2 alphabet
, David on an infinite
Perez-Garcia & Michael M. Wolf5 or lationally invariant Hamiltonian, with local interactions h(ϕ), that is
3,4 tape and moves left
right, following a finite set of rules. The halting problem asks: given an gapped or gapless depending on the value of ϕ. The local Hilbert space
initial input written on the tape, does the Turing machine halt? Turing of h(ϕ) is the tensor product of those of hu and hd together with one
Science, PNAS, proved that this problem is undecidable12; we relate it to the spectral additional energy level: H = |0〉 ⊕ H u ⊗ H d . We take the interaction
gap Theproblem in thegap—the
spectral followingenergyway. difference between the ground state h(i, j) between
and first nearest-neighbour
excited state of asites i and j to be
system—is central to quantum
many-body physics. Many challenging open problems, such as the Haldane conjecture, the question of the ,existence
and the Yang–Mills gaph(conjecture, ϕ )(i , j ) = |0〉〈0concern
|(i ) ⊗ (! −|spectral h(ui , j )(These
0〉〈0|)(j ) +gaps. ϕ ) ⊗ !(diand
j)

PLOS, ... Theorem


We can
D, and
of gapped
problems
1

a rational
topological spin liquid phases,
explicitlyareconstruct
particular a dimension
cases of
2
d, dthe 2
× dgeneral
matrices A, B, C and
spectral gap problem: given + the (iHamiltonian
, j)
! u ⊗ hd (i , j ) of a quantum many-body
other(1 )
system, is itnumber
gappedβ or > 0,gapless?
which can be chosen
Here we prove to be that
as small thisasis an undecidable problem. Specifically, we construct families
desired, such that spin systems on a two-dimensional lattice withThe
of quantum translationally invariant,
spectrum of the new Hamiltonian H is nearest-neighbour interactions,
2 Todas las revistas (ii)
A iswhich
(i)for
B and
such
(iii)
Hermitian,
asCthehave
D is Hermitian,
with matrix
integer matrix
existence
elements
the spectral gap problem is undecidable.
elements; and
of algebraically
in Z + β Z + β
2
Z ; This result extends to undecidability of other low-energy properties,
decaying ground-state correlations. specTheH = {0} proof ∪ {spec
combines Hu(ϕ ) +Hamiltonian
specHd } ∪ S complexity (2)
techniques withwith matrix elements
aperiodic tilings, to in construct
{0, 1, β}. a Hamiltonian whose ground state encodes the evolution of a quantum
For each positive integer n, define the local interactions of a transla-Turingwith S ≥ 1 (see Supplementary
spectral gapInformation forthedetails). Recalling that
de Matemáticas phase-estimation
tionally
lattice
invariant,
algorithm
nearest-neighbour
followed
Hamiltonian
as is gapped or gapless, and that there exist models for which
model
by a universal
H(n) on a 2D square we
machine.
chose
the ground
H
corresponding ‘halting problem’. Our result implies that there exists no algorithm to determine whether an arbitraryif d
The
to be gapless,
state energy
the presence
we see
density ofof
or absence
depends on
immediately
Huatends
spectral
from
to zero
outcome
equation
gapfrom
of the
(2) that
below (so that
is independent
λ0(Hu) < 0), then H(ϕ) is gapless; if Hu has a strictly positive ground
hof the axioms of mathematics.
1(n ) = α(n )Π state energy density (so that λ0(Hu) diverges to +∞), then it has a
3 Los profesores en h row = D
Thehcol spectral gap n) † important (n)| †
spectral gap
This Although
≥1,
construction
as required
one ismay rather
(see Fig.
general:
2).
by the
choosing different hd, wein
(e i πisϕ(one
B +ofe−πthe
i ϕ(most Cphysicali 2−| ϕproperties hard. be able to solve spectral gap problem
n) −| ϕ(n)|
=A+β B + e i π2 + e−π C )
of a quantum many-body system, determining much of its low- obtain specific undecidability
cases, our result of implies
any physical that itproperty
is, in general, that logically
distinguishes
impossi-a
sus apuntes (en energy
where ϕ(physics.
n ) = n/2Gapped
example,contains
expansion
|n |−1 is the

massive the
systems
excitations
rationalexhibit
number
and short-range
binary digits
non-critical
whose binary
of n after the correlations),
behaviourfraction
decimal point,whereas
(for Hamiltonian
|ϕ(n)|
ble to determine from whether
a gappedasystem
has two meanings, and we prove both.
systemwith a unique
is gapped productThis
or gapless. ground state.
statement

phase transitions
denotes the numberoccur when
of digits theexpansion,
in this spectral gap α(n) vanishes
≤ β is an and the sys- Encoding
algebraic computation
(1) The spectral gap problem in ground states undecidable: there
is algorithmically
la UCM y en tem exhibits
number
long-range
denote
that iscritical
computable
correlations).
Hermitian
behaviour
conjugation.
from(for
Many
n, Πexample,
Then
massless
is a projector andexcitations
the daggers
seminal results in condensed matter into
and Tocannotconstruct existthe
the local
actions,
anyHamiltonian
algorithm that,
interactions
determines whetherhu(ϕ)the
Hu(ϕ),given wea encode
of resultant
description
the Hamiltonian.
model isThe
the halting problem
of the local
halting
gapped
inter-
prob-
or gapless.
theory
(i) theprove
local that specificstrength
interaction systems are is ≤1gapped
(that or is,gapless,
h1(n ) ,forh row exam- lem
, hcol (n )concerns
This is
≤the1 same the dynamics
sense in which of a classical
the halting system—a
problemTuring machine.
is undecidable 12
.
todas partes) h1(n ) , h row , hple,
col(n that
extended
) ≤ 1);Heisenberg chain is gapless for half-integer spin1 (later To relate
the
to higherTuring
(ii) if the universal dimensions
machine 2
),halts
or that the 1D
on input AKLT
n, the (Affleck– quantum
Hamiltonian
(2) The it to
any consistent
the ground
spectral
system—we recursive
state energy
gap problem
construct
density—a static
is axiomatically
a Hamiltonian
axiomatization
property given
independent:
whose ground
of mathematics,
of a
therestate
exist
Kennedy–Lieb–Tasaki)
H(n) is gapped with γ ≥ 1; and model is gapped3. Similarly, many famous encodes particular the quantum
entire history of the computation
many-body Hamiltonians carried out bythe
for which thepresence
Turing
and long-standing open problems in theoretical physics concern the or absence of the spectral gap is not determined by these axioms. This
2 0presence
8 | NAT U orR absence
E | V O L of 5 2a8spectral
| 1 0 D Egap.C E MA BE paradigmatic
R 2015 example is is the form of undecidability encountered in Gödel’s incompleteness
13 reserved
the antiferromagnetic Heisenberg model in 1D with
© 2015 integerPublishers
Macmillan spins. Limited.
theorem .
All rights
The ‘Haldane conjecture’ that this model is gapped, first formulated
in 1983 , has yet to be rigorously proven despite strong supporting Precise statement of results
4
5
numerical evidence . The same question in the case of 2D non-bipartite It is important to be precise in what we mean by the spectral gap prob-
6
lattices such as the kagome lattice was posed in 1973 . Numerical lem. To this end, we must first specify the systems we are considering.
evidence7 strongly indicates that these systems may be topological Because we are proving undecidability, the simpler the system, the
David Gómez-Castro (UCM) Introducción a L TEX 2ε
spin liquids. This problem has attracted substantial A Diciembre 2018
attention8 because stronger the result. We restrict ourselves to nearest-neighbour, trans- 8 / 80
Descargar e instalar LATEX

Esta experiencia depende del sistema utilices: visita Latex project


Windows: MikTeX
Mac: MacTeX
Linux: a través del gestor software nativo de terminal
Debian/Ubuntu: sudo apt-get install texlive-full
RedHat/Fedora: yum install texlive-scheme-full
Suse: zypper install texlive-latex
Arch: pacman -S texlive-most
Otros: ¿en serio? ¿ninguno de los anteriores?. Te buscas la vida.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 9 / 80


Descargar el editor
TeXstudio

Durante esta lecciones utilizaremos el editor TeXstudio. Es libre y


gratuito1 .

Hay más opciones:


1 TeXShop
2 TexMaker
3 Gummy
4 Atom (requiere alguna configuración)
5 Emacs, Vim, etc... + compilación por terminal

1
Los usuarios de Linux lo pueden descargar por terminal
David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 10 / 80
TeXstudio

Figura: Interfaz de TeXstudio


David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 11 / 80
El archivo mı́nimo

Los archivos de LATEX son archivos de texto (plano) con extension .tex.

Aquı́ es donde decidimos que tipo de archivo latex queremos escribir, hay
diferentes tipos de documentos

Código
\documentclass{<style>}

% Configuracion del archivo

\begin{document}

% El texto

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 12 / 80


El archivo ¡Hola Mundo!

Aquı́ es donde decidimos qué tipo de archivo latex queremos escribir, hay
diferentes tipos de documentos

Código [hola-mundo.tex]
\documentclass{article}

\begin{document}

Hola Mundo

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 13 / 80


Compilando con TeXstudio

Figura: Compilar con TeXstudio


David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 14 / 80
Compilando en terminal

Navegar hasta la carpeta y escribir en terminal

latex hola-mundo.tex

En archivos más complicados hay que ejecutar el código varias veces

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 15 / 80


Cabecera y tipo de documento

En la cabecera introduciremos todo lo relativo a configuración

Código
\documentclass{<style>}

% Configuracion del archivo

\begin{document}

% El texto

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 16 / 80


Tipo de documento

Aquı́ es donde decidimos que tipo de archivo latex queremos escribir, hay
diferentes tipos de documentos

Código
\documentclass{<style>}
<style>:
1 article Para artı́culos % Configuracion del archivo
cortos. Acepta partes,
secciones y subsecciones \begin{document}

% El texto

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 17 / 80


Tipo de documento

Aquı́ es donde decidimos que tipo de archivo latex queremos escribir, hay
diferentes tipos de documentos

Código
<style>: \documentclass{<style>}

% Configuracion del archivo


2 book Para archivos más
extensos. Acepta partes, \begin{document}
capı́tulos, secciones,
subsecciones % El texto

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 17 / 80


El cuerpo

A partir de aquı́ escribiremos el texto

Código
\documentclass{<style>}

% Configuracion del archivo


Todo lo que queramos
escribir. \begin{document}

% El texto

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 18 / 80


Comandos y variables

Una herramienta fundamental en la escritura con LATEX


<command> Nombre del
comando
<opt> Argumento Código (llamada a comando)
optativo. \<command>[<opt>]{<arg1>}{<arg2>}
<arg> Argumento
obligatorio

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 19 / 80


Entornos

Los entornos funcionan como comandos, pero nos permiten introducir


cantidades más largas de texto.
Algunos ejemplos son
document: Es donde
introducimos el
Código
documento
\begin{<env>}[<opt>]
equation: Para
introducir ecuaciones
numeradas \end{<env>}
emph: Para conseguir
textos en cursiva.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 20 / 80


Los paquetes
Por defecto LATEX no incluye demasiados comandos ni entornos. Podemos
añadir nuevas funcionalidades (comandos y entornos) incluyendo
paquetes.

Uno de los paquetes más usuales es el paquete matemático de la American


Mathematical Society (AMS): amsmath.

Código
\documentclass{article}

\usepackage{amsmath}
3
X
\begin{document} ai = 1. (1)
i=1

\begin{equation}
\sum_{i=1}ˆ3 a_i = 1.
\end{equation}

\end{document}
David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 21 / 80
Creando comandos

Código
\documentclass{standalone}

\newcommand{\deciralgo}[1]
{Esto es lo que digo: ‘‘#1’’. Esto es lo que digo: “Hola”. Y no me arrepiento.

Y no me arrepiento.}

\begin{document}
\deciralgo{Hola}
\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 22 / 80


El fichero y compatibilidades
El paquete inputenc

Para mayor compatibilidad, especialmente entre sistemas operativos es


recomendable guardar los archivos de .tex en formato UTF8. Esto nos
permitirá poner acentos de manera sencilla.

Código
\documentclass{<style>}
Para indicarle al compilar que
hemos hecho eso escribimos. \usepackage[utf8]{inputenc}

\begin{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 23 / 80


El fichero y compatibilidades
El paquete inputenc

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 24 / 80


El paquete babel

Para que LATEX ponga todos los textos automáticos en castellano


deberemos añadir el paquete babel

Código
\documentclass{<style>}
Para indicarle al compilar que
hemos hecho eso escribimos. \usepackage[spanish]{babel}

\begin{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 25 / 80


Ficheros modulares: input
Escribir un libro completo en un único archivo no es cómodo. Por eso
LATEX permite escribir modularmente.
Podemos escribir en diferentes archivos .tex, y luego juntarlos en un
principal.

Código [modular.tex]
\documentclass{standalone}
\begin{document}
\input{modulo1.tex}
\input{modulo2.tex}
\end{document} Un texto. Otro texto.
Figura: Resultado de compilar
Código [modulo1.tex] modular.tex
Un texto.

Código [modulo2.tex]
Otro texto.
David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 26 / 80
Aspecto de un primer documento

Código (ejemplo1.tex)
\documentclass{article} Mi trabajo a LATEX
Yo
Y mi amigo

\usepackage[utf8]{inputenc} 23 de marzo de 2013

\usepackage[spanish]{babel} Este es el principio de mi trabajo.

\title{Mi trabajo a \LaTeX}


\author{Yo \\ Y mi amigo}
\date{\today}

\begin{document}

\maketitle

Este es el principio de mi trabajo.


1

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 27 / 80


Colaboración en LATEX
LATEX se lleva bien con la colaboración en Dropbox. Naturalmente, es
preferible que sólo una persona edite cada .tex. Por eso, en grupo, es
buena idea trabajar en módulos.

Otra opción es usar algún sistema online. Por ejemplo, Overleaf2 .

2
El sistema ShareLatex es ahora parte de Overleaf
David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 28 / 80
Sesión II

LATEX para Matemáticas

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 29 / 80


Escribiendo fórmulas

Hay diferentes entornos para escribir fórmulas:

1 En lı́nea Código
Puedo escribir $eˆ{i\pi } + 1
= 0$

Puedo escribir e iπ + 1 = 0

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 30 / 80


Escribiendo fórmulas

Hay diferentes entornos para escribir fórmulas:

Código
1 En lı́nea Puedo escribir
2 Presentada $$ eˆ{i\pi } + 1 = 0$$

Puedo escribir

e iπ + 1 = 0

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 30 / 80


Escribiendo fórmulas

Hay diferentes entornos para escribir fórmulas:

Código
Puedo escribir
1 En lı́nea \begin{equation}
2 Presentada eˆ{i\pi} + 1 = 0
3 equation \end{equation}

Puedo escribir

e iπ + 1 = 0 (1)

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 30 / 80


Escribiendo fórmulas

Hay diferentes entornos para escribir fórmulas:

Código
Puedo escribir
\begin{align}
1 En lı́nea eˆ{i\pi} + 1 &= 0 \\
2 Presentada eˆ{i\pi} &= -1
\end{align}
3 equation
4 align Puedo escribir

e iπ + 1 = 0 (1)

e = −1 (2)

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 30 / 80


Sı́mbolos útiles

a
+ + ε \varepsilon \frac{a}{b}
√b
− - δ \delta a \sqrt{a}
× \times ∂ \partial ab {a}ˆ{b}
÷ \div Ω \Omega
· \cdot π \pi
⊕ \oplus
⊗ \otimes

La web Detexify permite buscar sı́mbolos a partir de un dibujo a mano


alzada.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 31 / 80


La ecuación más bella del mundo

La ecuación de Euler, popular por contener algunas de las más importantes


constantes matemáticas puede escribirse

Código e iπ + 1 = 0
eˆ{i\pi} + 1 = 0
Puedo escribir la ecuación de
Código Euler e iπ + 1 = 0 en lı́nea o
Puedo escribir la ecuación presentada
de Euler $eˆ{i \pi} + 1 = 0$
en lı́nea o presentada e iπ + 1 = 0
$$ eˆ{i\pi} + 1 = 0$$
para que quede mejor para que quede mejor

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 32 / 80


Subı́ndices y superı́ndices
Los subı́ndices de sumarios e integrales cambian de formato presentado a
en lı́nea
Rb
En lı́nea digo ni=1
P
Código a mien-
En lı́nea digo tras que presentado
$\sum_{i=1}ˆn \int_aˆb$
mientras que presentado n Z b
X
$$ \sum_{i=1}ˆn \int_aˆb $$
i=1 a

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 33 / 80


Subı́ndices y superı́ndices
Los subı́ndices de sumarios e integrales cambian de formato presentado a
en lı́nea
Rb
En lı́nea digo ni=1
P
Código a mien-
En lı́nea digo tras que presentado
$\sum_{i=1}ˆn \int_aˆb$
mientras que presentado n Z b
X
$$ \sum_{i=1}ˆn \int_aˆb $$
i=1 a

Además la función \substack es muy útil

Código máx
$$\max_{\substack{y \in \Omega \\ |y| > 1}}$$ y ∈Ω
|y |>1

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 33 / 80


Matrices

Las matrices se introducen siempre en entornos matemáticos. Maple y


matlab permiten exportar matrices a LATEX. Hay distintos tipos de matrices
predeterminadas en el paquete amsmath.
1 matrix Sin bordes
2 pmatrix Entre ()
3 vmatrix Entre | |
4 bmatrix Entre [ ]

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 34 / 80


Matrices
Ejemplo

Código
$$  
\begin{pmatrix} 1 2 3
4 5
 
1 & 2 & 3 \\ 
4 & 5 & \\ 6 7
6 & & 7
\end{pmatrix}
$$

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 35 / 80


Matrices
Ejemplo

Código
$$  
\begin{bmatrix} 1 2 3
4 5
 
1 & 2 & 3 \\ 
4 & 5 & \\ 6 7
6 & & 7
\end{bmatrix}
$$

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 36 / 80


El paquete xy-pic

Este paquete se emplea para hacer todo tipo de gráficos, por ejemplo el
diagrama
A
f /B
g
g◦f  
C
Tiene infinidad de opciones.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 37 / 80


xymatrix

Es la manera más sencilla de introducir diagramas. Los elementos que se


conectarán por flechas se introducen en las posiciones de una matriz, de
tipo xymatrix

Código A B
\xymatrix{
A & B \\
& C C
}
Se puede introducir una xymatrix dentro o fuera de fórmulas, pero
deberemos tener cuidado con el contenido.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 38 / 80


Las flechas
Dentro de una xymatrix podemos introducir flechas con el comando \ar
Admite varios modificadores
1 Destino Colocando la
flecha en la casilla de la
que parte se coloca un
cadena de cuantas
casillas a derecha o u arriba
izquierda y arriba o d abajo
abajo está el destino. r derecha
\ar [<hop>] l izquierda
a si misma

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 39 / 80


Las flechas

Dentro de una xymatrix podemos introducir flechas con el comando \ar


Admite varios modificadores
1 Destino
2 Etiqueta Se puede \ar [r]ˆ{f} a
f /b
escribir sobre las letras \ar [r]_{f} a /b
f
\ar [r]|{f} a f /b

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 39 / 80


Las flechas

Dentro de una xymatrix podemos introducir flechas con el comando \ar


Admite varios modificadores
1 Destino
@{=>} a +3 b
2 Etiqueta
@{.>} a /b
3 Tipo Hay distintos tipos
@{:>} a +3 b
de base, cuerpos y
cabezas de flecha @{˜>} a /b
\ar @{<type>}[<hop>] @{-->} a /b
@{|->} a /b

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 39 / 80


Las flechas

Dentro de una xymatrix podemos introducir flechas con el comando \ar


Admite varios modificadores
1 Destino
2 Etiqueta
3 Tipo
4 Curvatura Podemos @/_/ a 6b
curvar las flechas hacia @/ˆ/ (
a b
arriba y hacia abajo,
@/_1mm/ a 2b
para evitar que se
corten, o solo para quede
más estiloso \ar
@/<curve>/ [<hop>]

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 39 / 80


Las flechas

Dentro de una xymatrix podemos introducir flechas con el comando \ar


Admite varios modificadores
1 Destino
2 Etiqueta
3 Tipo
4 Curvatura
5 Entrada y salida Si @(u,d)[r] a bL
queremos que la flecha @(ur,dr)[] ad b
salga desde una parte en
concreto de la celda
podemos especificarlo
\ar
@(<in>,<out>)[<hop>]

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 39 / 80


Las flechas
Ejercicio
Escriba el siguiente diagrama:

f
 ! y
B _ /C id

 
D

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 40 / 80


Las flechas
Ejercicio
Escriba el siguiente diagrama:

f
 ! y
B _ /C id

 
D

Código (ejercicio3.tex)
$$
\xymatrix{
A \ar@/_2ex/[ddr] \ar[dr]|f \ar@/ˆ2ex/[drr] \\
& B \ar@{-->}[r] \ar@{ˆ(->}[d] & C\ar@(dr,ur)[]_{id} \\
& D
}
$$

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 40 / 80


El paquete xy-pic y el paquete babel

El paquete babel entra en conflicto con @ ası́ que si queremos hacer


buenos diagramas debemos desactivarlo. Empleando inputenc con utf8
no tendremos problemas con los acentos. Debemos cambiar los nombres
de capı́tulos y secciones. Para ello \renewcommand
{<command>}{<new_name>}

\abstractname Abstract
\appendixname Appendix
\bibname Bibliography (report,book)
\chaptername Chapter (report,book)
\contentsname Contents
\figurename Figure (for captions)
\indexname Index
\listfigurename List of Figures
\listtablename List of Tables
\tablename Table (for caption)

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 41 / 80


Teoremas
El paquete amsthm

A la hora definir un teorema debemos tener en cuenta tres cosas


1 El estilo: Los teoremas Código
se escriben en cursiva,
\documentclass
mientras que las (...)
definiciones se escriben \theoremstyle {<style>}
con fuente normal. \newtheorem {<env>}{<name>}
(...)
\begin {document}
Hay tres estilos predefinidos:
plain Theorem 1.Theorem text.
definition Definition 1. Definition text.
remark Remark 1.Remark text.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 42 / 80


Teoremas
El paquete amsthm

A la hora definir un teorema debemos tener en cuenta tres cosas


1 El estilo
2 El nombre: Debemos
poner un nombre de Código
entorno <env>, ya sea \documentclass
teorema (por ejemplo (...)
<env>=teorema) un \theoremstyle {<style>}
nombre para mostrar en \newtheorem {<env>}{<name>}
el documento (por (...)
ejemplo \begin {document}
<name>=Teorema)

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 42 / 80


Teoremas
El paquete amsthm

A la hora definir un teorema debemos tener en cuenta tres cosas


Código
1 El estilo
\documentclass
2 El nombre (...)
3 La numeración: Podemos \theoremstyle {<style>}
numerar los teoremas de \newtheorem {<env>}{<name>}
(...)
diferentes maneras
\begin {document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 42 / 80


Teoremas
El paquete amsthm

A la hora definir un teorema debemos tener en cuenta tres cosas


1 El estilo
2 El nombre
3 La numeración
a) Con su propio contador: Código
El contador se crea por
defecto si no decimos \documentclass
nada más, y se nombra (...)
automáticamente como \theoremstyle {<style>}
<env> \newtheorem {<env>}{<name>}
(...)
\begin {document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 42 / 80


Teoremas
El paquete amsthm

A la hora definir un teorema debemos tener en cuenta tres cosas


1 El estilo
2 El nombre Código
3 La numeración \documentclass
a) Con su propio contador: (...)
b) Siguiendo la \theoremstyle {<style>}
numeración de otro \newtheorem {<env>} [<counter>]{<name>}
teorema ya definido (...)
\begin {document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 42 / 80


Teoremas
El paquete amsthm
A la hora definir un teorema debemos tener en cuenta tres cosas
1 El estilo
2 El nombre
3 La numeración
a) Con su propio contador:
b) Siguiendo la Código
numeración de otro \documentclass
teorema ya definido (...)
c) Supeditada a otro \theoremstyle {<style>}
contador, por ejemplo \newtheorem {<env>}{<name>}[<counter>]
la sección. En este caso (...)
el contador de tipo a) \begin {document}
lleva como predecesor
el otro contador, y se
resetea al cambiar el
contador al que
supedita
David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 42 / 80
Teoremas
Ejemplo

Este es el aspecto de un teorema normal definido con el paquete amsthm.

Código (ejemplo2.tex)
\documentclass{article}
\usepackage{amsthm}

\theoremstyle{plain} Teorema 1 (Euclides) . No


\newtheorem{teorema}{Teorema}
existe un primo mayor que el
\begin{document} resto.
\begin{teorema}[Euclides]
No existe un primo mayor que el resto.
\end{teorema}

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 43 / 80


Operadores matemáticos

Con el paquete amsmath se pueden definir operadores matemáticos, como


div o rot:

\DeclareMathOperator {\rot }{rot}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 44 / 80


Ejercicio

Escribir el siguiente documento LATEX

El teorema de la divergencia
Un estudiante
10 de abril de 2013

1. El teorema
El teorema de la divergencia de Gauss se enuncia de la siguiente manera

Teorema 1.1. Dado ....


Demostración. La prueba...

2. Ejercicios
Ejercicio 1. Este ejercicio

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 45 / 80


Solución

Código Código (ejemplo3.tex)


(ejercicio1.tex) \section{El teorema}

\documentclass{article} El teorema de la divergencia de Gauss


se enuncia de la siguiente manera
\usepackage[spanish]{babel}
\usepackage[utf8]{inputenc} \begin{thm}
\usepackage{amsthm} Dado ....
\end{thm}
\theoremstyle{plain} \begin{proof}
\newtheorem{thm}{Teorema}[section] La prueba...
\theoremstyle{definition} \end{proof}
\newtheorem{ex}{Ejercicio}
\section{Ejercicios}
\title{El teorema de la divergencia}
\author{Un estudiante} \begin{ex}
Este ejercicio
\begin{document} \end{ex}
\maketitle
\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 46 / 80


Sesión III

LATEX como editor de texto


avanzado

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 47 / 80


Flotantes y su localización
Los objetos con los que vamos a trabajar: figuras, tablas, etc... se conocen como
flotantes.

Por defecto LATEX los coloca donde menos moleste: en el lugar del texto donde
hemos colocado el código, al principio de la página o al final de la página.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 48 / 80


Flotantes y su localización
Los objetos con los que vamos a trabajar: figuras, tablas, etc... se conocen como
flotantes.

Por defecto LATEX los coloca donde menos moleste: en el lugar del texto donde
hemos colocado el código, al principio de la página o al final de la página.

Podemos especificar dónde colocarlos mediante parámetros optativos:


\begin {figure}[placement specifier].

Las opciones son las siguientes


Specifier Permission
h Place the float here (approximately at the same point it occurs in the source text)
t Position at the top of the page.
b Position at the bottom of the page.
p Put on a special page for floats only.
! Override internal parameters LaTeX uses for determining “good” float positions.
H Places the float at precisely the location in the LaTeX code. Requires the float package.

También se admiten cadena htb significa: inténtalo en su sitio, si no ponlo arriba


y, si no, abajo.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 48 / 80


Figuras

Para incluir imágenes empleamos el paquete graphicx. Si empleamos el


compilador pdflatex. Podemos emplear imágenes .pdf, .png.
Tiene los siguientes parámetros:
1 <path> Es la dirección del

archivo a incluir. Lo mejor es Código


escribirla relativa al directorio \begin{figure}[h!]
esto es <path>=archivo.pdf \includegraphics [scale= <scale>] {<path>}
\caption {<caption>}
\end {figure}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 49 / 80


Figuras

Para incluir imágenes empleamos el paquete graphicx. Si empleamos el


compilador pdflatex. Podemos emplear imágenes .pdf, .png.
Tiene los siguientes parámetros:
1 <path> Código
2 <scale> Valor entre 0 y 1 al \begin{figure}[h!]
\includegraphics [scale= <scale>] {<path>}
que escalar la figura. \caption {<caption>}
\end {figure}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 49 / 80


Figuras

Para incluir imágenes empleamos el paquete graphicx. Si empleamos el


compilador pdflatex. Podemos emplear imágenes .pdf, .png.
Tiene los siguientes parámetros:
1 <path>
2 <scale> Código
\begin{figure}[h!]
3 <caption> El contenido de \includegraphics [scale= <scale>] {<path>}
\caption {<caption>}
<caption> será el pie de foto, \end {figure}
es decir, aparecerá Figura x:
caption

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 49 / 80


Figura
Ejemplo

Código
\documentclass{article}

\usepackage{graphicx}

\begin{document}

\begin{figure}

\centering
\includegraphics[scale=0.5]
{gauss.pdf} Figure 1: Gauss
\caption{Gauss}

\end{figure}

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 50 / 80


Tablas

Las el entorno table es equivalente a figura, pero al generar el caption


obtendremos Cuadro (como recomiendo la RAE).

En contenido de la tabla se introduce de manera similar a una matriz


1 <align>:

a) l: izquierda Código
b) c: centrado \begin{tabular}{<align>| ... }
c) r: derecha cuadro1 & cuadro2 & ... \\
\hline\\
...
\end{tabular}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 51 / 80


Tablas

Las el entorno table es equivalente a figura, pero al generar el caption


obtendremos Cuadro (como recomiendo la RAE).

En contenido de la tabla se introduce de manera similar a una matriz


1 <align>: Código
2 & Separación entre \begin{tabular}{<align>| ... }
cuadros en la misma fila cuadro1 & cuadro2 & ... \\
\hline\\
...
\end{tabular}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 51 / 80


Tablas

Las el entorno table es equivalente a figura, pero al generar el caption


obtendremos Cuadro (como recomiendo la RAE).

En contenido de la tabla se introduce de manera similar a una matriz


1 <align>:
Código
2 & \begin{tabular}{<align>| ... }
3 | Si se desea lı́nea cuadro1 & cuadro2 & ... \\
vertical entre dos \hline\\
columnas ...
\end{tabular}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 51 / 80


Tablas

Las el entorno table es equivalente a figura, pero al generar el caption


obtendremos Cuadro (como recomiendo la RAE).

En contenido de la tabla se introduce de manera similar a una matriz


1 <align>: Código
2 & \begin{tabular}{<align>| ... }
cuadro1 & cuadro2 & ... \\
3 | \hline\\
4 \hline Si se desea una ...
lı́nea horizontal. \end{tabular}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 51 / 80


Tablas
Ejemplo

Código
\begin{table}

\begin{tabular}{c|l r|} 1 2 3
1 & 2 & 3 \\ 4 5
\hline 6 7
4 & 5 & \\
6 & & 7 Cuadro: Mi tabla
\end{tabular}

\caption{Mi tabla}
\end{table}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 52 / 80


Añadir código
El paquete listing nos permite introducir código de diferentes lenguajes

Código
\documentclass{standalone}

\usepackage{listings}

\begin{document} #i n c l u d e <s t d i o . h>


main ( )
\begin{lstlisting} {
#include<stdio.h> p r i n t f ( ” H e l l o World ” ) ;
main() }
{
printf("Hello World"); Figura: Resultado de compilar
}
\end{lstlisting}

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 53 / 80


Añadir código
También se puede cargar de un fichero externo

Código [ejemplo-c-2.tex]
\documentclass{standalone}

\usepackage{listings}
#include<s t d i o . h>
\begin{document} main ( )
\lstinputlisting[language=C++]{codigo2.cpp}
{
\end{document}
p r i n t f ( ” H e l l o World” ) ;
}
Código [codigo2.cpp]
#include<stdio.h> Figura: Resultado de compilar
main() ejemplo-c-2.tex
{
printf("Hello World");
}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 54 / 80


Añadir código: Colores
Código
\documentclass{standalone}
\usepackage{listings,xcolor}
\begin{document}

\lstset{language=C++,
keywordstyle=\color{blue},
stringstyle=\color{red}, #i n c l u d e <s t d i o . h>
commentstyle=\color{green}, main ( )
morecomment=[l][\color{magenta}]{\#} {
} p r i n t f ( ” H e l l o World” ) ;
\begin{lstlisting} }
#include<stdio.h>
main() Figura: Resultado de compilar
{
printf("Hello World");
}
\end{lstlisting}

\end{document}
David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 55 / 80
Añadir código MATLAB
MathWorks ofrece un paquete (a descargar aquı́) para incluir código con
formato de matlab
Código[Ejemplo de mcode]
\documentclass{standalone}

\usepackage{listing}
\usepackage{xcolor}
\usepackage{mcode}
% Mi codigo matlab
\begin{document} a = 1;
\lstinputlisting{codigo1.m}
\end{document} Figura: Resultado de compilar
ejemplo-mcode.tex

Código[codigo1.m]
% Mi codigo matlab
a = 1;

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 56 / 80


Secciones e ı́ndices
Naturalmente LATEX permite estructurar el documento en secciones.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 57 / 80


Secciones e ı́ndices
Naturalmente LATEX permite estructurar el documento en secciones.

Para empezar una nueva sección con tı́tulo basta con indicarlo y dar un
tı́tulo utilizando los siguientes comandos:
-1 \part {titulo}
0 \chapter {titulo}
1 \section {titulo}
2 \subsection {titulo}
3 \subsubsection {titulo}
4 \paragraph {titulo}
5 \subparagraph {titulo}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 57 / 80


Secciones e ı́ndices
Naturalmente LATEX permite estructurar el documento en secciones.

Para empezar una nueva sección con tı́tulo basta con indicarlo y dar un
tı́tulo utilizando los siguientes comandos:
-1 \part {titulo}
0 \chapter {titulo}
1 \section {titulo}
2 \subsection {titulo}
3 \subsubsection {titulo}
4 \paragraph {titulo}
5 \subparagraph {titulo}
Se puede generar el ı́ndice introduciendo \tableofcontents . Este
comando admite parámetros optativos.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 57 / 80


Secciones e ı́ndices
Naturalmente LATEX permite estructurar el documento en secciones.

Para empezar una nueva sección con tı́tulo basta con indicarlo y dar un
tı́tulo utilizando los siguientes comandos:
-1 \part {titulo}
0 \chapter {titulo}
1 \section {titulo}
2 \subsection {titulo}
3 \subsubsection {titulo}
4 \paragraph {titulo}
5 \subparagraph {titulo}
Se puede generar el ı́ndice introduciendo \tableofcontents . Este
comando admite parámetros optativos.

También se pueden hacer otras tablas de contenidos: \listoffigures ,


\listoftables .
David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 57 / 80
El paquete fancyhdr

Una forma sencilla de darle un buen estilo a nuestro archivo es emplear el


paquete fancyhdr. Tiene varias opciones, lo más sencillo es emplear un
paquete predefinido

Código
\usepackage{fancyhdr}
\pagestyle{<style>}

<style>:
Encabezado Pie de página
empty Vacı́o Vacı́o
plain Vacı́o Número de página centrado
headings Nombre del capı́tulo y número de página Vacı́o
myheadings Número de página y otros Vacı́o
fancy Capı́tulo y sección Número de página

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 58 / 80


El formato de la Facultad
La Facultad va a incorporar un formato de TFG en el que toda el formato
necesario va preparada en la clase UCMmatTFG.

Código. Uso de UCMmatTFG


\documentclass{clases/UCMmatTFG}

[...]
\begin{document}
[...]
%% ************************* Capitulos *************************
%% Se recomienda escribir cada capitulo en un archivo distinto
%% para evitar grandes tamano de archivos

\pagestyle{cuerpo-tfg} %Cambiar formato de pagina

% Introducimos el primer capitulo


\input{cap1/intro}

% Capitulo 2
\input{cap2/cap2}

% Capitulo 3
%\input{cap3/cap3}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 59 / 80


Sesión IV

Referencias

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 60 / 80


Referencias

Para establecer una etiqueta a la que poder llamar se emplea


\label{<label>}
Es habitual emplear etiquetas de la forma
<label>=thm:euclides, fig:gauss, eq:divergencia
No se pueden emplear acentos.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 61 / 80


Referencias
Ejemplo

Código
\begin{figure}
Código
\begin{<thm>} \label{<label>} \includegraphics{<path>}
\caption{<caption>}
\end{<thm>} \label{<label>}

\end{figure}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 62 / 80


Referencias: El comando \ref
Podemos llamar al número de una etiqueta mediante \ref {<label>}.

Ejercicio: Escribir el código


correspondiente a la siguiente salida:

Teorema 1 No hay primo mayor que el resto

Figura 1: Euclides

Euclides, al que podemos ver en la Figura 1, propuso y demostró el Teorema 1.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 63 / 80


Referencias: El comando \ref
Podemos llamar al número de una etiqueta mediante \ref {<label>}.

Solución
\documentclass{article} Ejercicio: Escribir el código
\usepackage[spanish]{babel} correspondiente a la siguiente salida:
\usepackage[utf8]{inputenc}
\usepackage{graphicx}

\newtheorem{thm}{Teorema} Teorema 1 No hay primo mayor que el resto

\begin{document}

\begin{thm} \label{thm:euclides}
No hay primo mayor que el resto
\end{thm}
\begin{figure}[h!]
\centering
\includegraphics[scale=0.5]{euclides.pdf} Figura 1: Euclides

\caption{Euclides} Euclides, al que podemos ver en la Figura 1, propuso y demostró el Teorema 1.


\label{fig:euclides}
\end{figure}
Euclides, al que podemos ver en la
Figura˜\ref{fig:euclides}, propuso
y demostró el Teorema˜\ref{thm:euclides}.

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 63 / 80


Referencias avanzadas: el paquete \cleveref
Introduciendo este paquete tenemos acceso al comando \Cref .

Esta función actúa como \ref , pero incluye automáticamente el tipo de


objeto referenciado: Teorema, Figura...

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 64 / 80


Referencias avanzadas: el paquete \cleveref
Introduciendo este paquete tenemos acceso al comando \Cref .

Esta función actúa como \ref , pero incluye automáticamente el tipo de


objeto referenciado: Teorema, Figura...
Código
\documentclass{article}
\usepackage[spanish]{babel}
\usepackage[utf8]{inputenc}
\usepackage{graphicx} Teorema 1 No hay primo mayor que el resto
\usepackage[spanish]{cleveref}
\newtheorem{thm}{Teorema}
\begin{document}

\begin{thm} \label{thm:euclides}
No hay primo mayor que el resto
\end{thm}
\begin{figure}[h!]
\centering Figura 1: Euclides
\includegraphics[scale=0.5]{euclides.pdf}
Euclides, al que podemos ver en la Figura 1, propuso y demostró el Teorema 1.
\caption{Euclides}
\label{fig:euclides}
\end{figure}
Euclides, al que podemos ver en la
\Cref{fig:euclides}, propuso
y demostró el \Cref{thm:euclides}.

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 64 / 80


Bibliografı́a nativa

Código
\documentclass{article}
\begin{document}

Cito el art\’iculo \cite{latexcompanion} Cito el artı́culo [1]

\begin{thebibliography}{9} References
\bibitem{latexcompanion} [1] Michel Goossens, Frank Mittelbach, and Alexander Samarin. The LATEX
Michel Goossens, Frank Mittelbach, Companion. Addison-Wesley, Reading, Massachusetts, 1993.

and Alexander Samarin. [2] Albert Einstein. Zur Elektrodynamik bewegter Körper. (German) [On the
electrodynamics of moving bodies]. Annalen der Physik, 322(10):891921,
\textit{The \LaTeX\ Companion}. 1905.
Addison-Wesley, Reading, Massachusetts, 1993. [3] Wikipedia
http://www.wikipedia.com
\bibitem{einstein}
Albert Einstein.
\textit{Zur Elektrodynamik bewegter K{\"o}rper}.
(German)
[{On the electrodynamics of moving bodies}].
Annalen der Physik, 322(10):891{921, 1905.

\bibitem{wikipedia}
Wikipedia
\\\texttt{http://www.wikipedia.com}
\end{thebibliography}
\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 65 / 80


Bibtex: formato automático
Código
[ejemplo-bibtex.tex]
Cito el artı́culo [1].
\documentclass{article}
\begin{document} References
[1] Albert Einstein. Zur Elektrodynamik bewegter Körper. (German) [On the
Cito el art\’iculo \cite{einstein}. electrodynamics of moving bodies]. Annalen der Physik, 322(10):891–921,
1905.
\bibliographystyle{plain}
\bibliography{ejemplo-bibliografia.bib}
\end{document}

Código
[ejemplo-bibliografia.bib]
@article{einstein,
author = "Albert Einstein",
title = "{Zur Elektrodynamik bewegter K{\"o}rper}.
({German})
[{On} the electrodynamics of moving bodies]",
journal = "Annalen der Physik", Observación. Bibtex, al compilar,
volume = "322",
number = "10",
genera un archivo .bbl que contiene
pages = "891--921",
year = "1905",
una bibliografı́a nativa.
DOI = "http://dx.doi.org/10.1002/andp.19053221004"
}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 66 / 80


Sesión V

Presentaciones con LATEX

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 67 / 80


El paquete beamer

El paquete beamer nos permite hacer presentaciones en LATEX como esta.

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 68 / 80


La cabecera
Una cabecera elemental

Código
\documentclass{beamer}

\usepackage[utf8]{inputenc}

\mode<presentation>
\usetheme{Warsaw}
\usecolortheme{seahorse}

\title{Mi presentacion}
\author{Yo}
\date{\today}

Para ver diferentes estilos y colores visitar


https://hartwork.org/beamer-theme-matrix/

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 69 / 80


La cabecera
Una cabecera completa

Código
\documentclass{beamer}

\usepackage[utf8]{inputenc}
\usepackage[spanish]{babel}
\usepackage{amsthm}
\usepackage{graphicx}
\newtheorem{thm}{Teorema}

\mode<presentation>
\usetheme{Warsaw}
\usecolortheme{seahorse}

\title{Mi presentacion}
\author{Yo}
\date{\today}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 70 / 80


Las diapositivas

Las diapositivas se introducen en un entorno frame. Algunas cosas que se


pueden añadir (editando la cabecera acordemente)

Código
\begin{document}

\begin{frame}
% Texto de la diapositiva
\end{frame}

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 71 / 80


Las diapositivas

Las diapositivas se introducen en un entorno frame. Algunas cosas que se


pueden añadir (editando la cabecera acordemente)

Código
1 Cuadros \begin{frame}
\begin{block}{Bloque}
Texto en un bloque
\end{block}
\end{frame}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 71 / 80


Las diapositivas

Las diapositivas se introducen en un entorno frame. Algunas cosas que se


pueden añadir (editando la cabecera acordemente)

Código
\begin{frame}
\begin{figure}
1 Cuadros
\centering
2 Imágenes \includegraphics[scale=0.5]
{gauss.pdf}
\caption{Gauss}
\end{figure}
\end{frame}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 71 / 80


Las diapositivas

Las diapositivas se introducen en un entorno frame. Algunas cosas que se


pueden añadir (editando la cabecera acordemente)

Código
\begin{frame}
\begin{thm}
1 Cuadros
Un teorema...
2 Imágenes \end{thm}
\begin{proof}
3 Teoremas
Y su prueba ...
\end{proof}
\end{frame}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 71 / 80


Sesión VI

Gráficos avanzados

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 72 / 80


El paquete Tikz

El paquete tikz nos permite general dibujos

Código
\documentclass{standalone} % say

\usepackage{tikz}

\begin{document}
Trabajaremos con

\begin{tikzpicture}
\draw (-1.5,0) -- (1.5,0); Trabajaremos con .
\draw (0,-1.5) -- (0,1.5);
\end{tikzpicture}. Figura: Resultado de compilar

\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 73 / 80


Dibujo libre

Existen diferentes tipos de lı́neas y figuras, las opciones son ilimitadas

Código
\begin{tikzpicture}
\draw[->] (-1.5,0) -- (1.5,0);
\draw[dashed] (0,-1.5) -- (0,1.5);
\draw[green] (0,0) circle (1cm);
\end{tikzpicture}

Bellos ejemplos se pueden encontrar en


http://www.texample.net/tikz/examples/

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 74 / 80


Representación de grafos
Código
\documentclass[tikz,border=10pt]{standalone}
\usetikzlibrary{positioning}
\tikzset{main node/.style={circle,fill=blue!20,draw,minimum size=1cm,inner sep=0pt},}
\begin{document}
\begin{tikzpicture}
\node[main node] (1) {$1$};
\node[main node] (2) [below left = 2.3cm and 1.5cm of 1] {$2$};
\node[main node] (3) [below right = 2.3cm and 1.5cm of 1] {$3$};

\path[draw,thick]
(1) edge node {} (2)
(2) edge node {} (3)
(3) edge node {} (1);
\end{tikzpicture}
\end{document}

2 3

Figura: Resultado de compilar

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 75 / 80


Diagramas de flujo

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 76 / 80


Desvarı́os excesivos

Poincaré Diagram: Classification of Phase Portraits in the (det A, Tr A)-plane

det A
∆=0 ∆=0: det A= 14 (Tr A)2

spiral sink spiral source


degenerate sink degenerate source

uniform center
motion

sink source
Tr A

line of stable fixed points saddle line of unstable fixed points

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 77 / 80


Representación de curvas
Código
\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw[->] (-3,0) -- (4.2,0) node[right] {$x$};
\draw[->] (0,-3) -- (0,4.2) node[above] {$y$};
\draw[scale=0.5,domain=-3:3,smooth,variable=\x,blue] plot ({\x},{\x*\x});
\draw[scale=0.5,domain=-3:3,smooth,variable=\y,red] plot ({\y*\y},{\y});
\end{tikzpicture}
\end{document}

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 78 / 80


Representación de funciones: pgfplots

Código
8
\documentclass{standalone}
\usepackage{pgfplots} 6

4
\begin{document}
\begin{tikzpicture} 2

\begin{axis}[xmax=9,ymax=9,samples=50] 0
\addplot[blue] (x,x*x);
−2
\addplot[red] (x*x,x);
\end{axis} −4
−4 −2 0 2 4 6 8
\end{tikzpicture}
\end{document}
Figura: Resultado de compilar

Una buena lista de ejemplos del manual:


http://pgfplots.sourceforge.net/gallery.html

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 79 / 80


Representación de datos
Código
\documentclass{standalone}
\usepackage{pgfplots}

\begin{document}
6
\begin{tikzpicture}
\begin{axis}
\addplot
4
table [x=a, y=c, col sep=comma]
{data.csv};
\end{axis}
\end{tikzpicture} 2
\end{document}

1 2 3 4 5
Código [data.csv]
a,b,c,d Figura: Resultado de compilar
1,4,5,1
2,3,1,5
3,5,6,1
4,1,4,9
5,3,4,7

David Gómez-Castro (UCM) Introducción a LATEX 2ε Diciembre 2018 80 / 80

Vous aimerez peut-être aussi