## Archive Page 2

### Mess up Matlab codes and outputs in LaTeX

You do not want to mess up, right? When writing a LaTeX document, you may once in a while want to include some Matlab codes and/or outputs (preferably typeset using typewriter font if you have the same taste as me) during the course of your writing. What I used to do was to copy and paste the Matlab codes into my LaTeX file, execute the codes in Matlab, then do another copy and paste to place the results in my LaTeX file, and finally decorate them in a verbatim block or something like that. Guess what, Matlab provides a command, called publish, that helps you do all these in a simpler way.

In a nutshell, the way to use publish is to first type in the texts (as your usually LaTeX editing), including Matlab codes, in a single .m file. Let’s say the file name is example.m. Then, in Matlab, you issue the command

publish('example.m', struct('format','latex','outputDir','ltx-src'));

It means that you want Matlab to process example.m and output a LaTeX file example.tex (that you can compile to get pdf) in the sub-directory ltx-src. This is it. Instead of writing example.tex, you write a file example.m.

So, how should I write example.m? It is best to give an example. See the following:

%% % <latex> % The eigenvalues of a circulant matrix can be % obtained by performing FFT on the first column % of the matrix. First, let us construct a % $5\times5$ circulant matrix \verb|C| whose first % column \verb|c| is generated with random input: % </latex> 

c = rand(5,1); % sad that Matlab does not provide a circulant() % command... C = toeplitz(c, c([1 end:-1:2]))

%% % <latex> % The eigenvalues of \verb|C| are nothing but % </latex>

lambda = fft(c)

%% % <latex> % Check it out! The output is the same as using % the \verb|eig| command: % </latex>

eig(C)

%% % Fun, isn't it? 

It is nothing but a script file that Matlab can execute, right? The trick part is that all the texts and LaTeX markups are buried in comment blocks. How the Matlab command publish makes a LaTeX output is that whenever it meets a whole block of comments starting with ‘%%‘, it strips the comment signs and decorates the whole block using the pair \begin{par} and \end{par}. On the other hand, whenever it meets a block of codes that does not start with ‘%%‘, Matlab knows that they are executable commands. Matlab uses \begin{verbatim} and \end{verbatim} to typeset these command texts, and automatically add the Matlab outputs of the commands, which are also decorated by the \begin{verbatim} and \end{verbatim} pair, in the LaTeX file. Something I am not satisfied is that Matlab does not recognize LaTeX commands such as \verb||. I have to put <latex></latex> so that Matlab can do a verbatim copy of \verb||, instead of expand the text \verb|| in some weird way, in the output LaTeX file.

It is time to try the above example yourself. Have fun.

### Call by value or call by reference?

In C, if you pass in a pointer to a function, the content of the involved variable may be changed. In Matlab, however, if you pass in an array as an argument, the content of the array will never be changed after the function call, even if the variable with the same name is modified within the function, unless the variable is also output. Ok, now comes the question: What if the function called by Matlab is written in C as a mex function? Haha, have fun with the following three tests, t1, t2, and t3.

/* File: t1.c */ #include 

void foo(double *a) { a[0] = 1; }

 void main(void) { double a[2] = {0}; foo(a); printf("first element of array a = %g\n", a[0]); } 

% File: t2.m function t2()

a = zeros(2,1); foo(a); fprintf(1, 'first element of array a = %g\n', a(1));

function foo(a)

 a(1) = 1; 

% File: t3.m function t3()

 a = zeros(2,1); foo_mex(a); fprintf(1, 'first element of array a = %g\n', a(1)); 

/* File: foo_mex.c */ #include "mex.h"

 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *a = mxGetPr(prhs[0]); a[0] = 1; } 

### A sample MATLAB code for defining functions with cases

The code should be self-explaning..

function y = f(x) y1 = x.* (x<0); y2 = x.^2 .* (x>=0) .* (x<2); y3 = 4 .* (x>=2); y = y1 + y2 + y3; 

### A few old LaTeX posts

I decided it would be beneficial to post some articles that I had written and posted elsewhere quite long ago.  This idea came from someone asking me today “How to change the font of an article from computer modern to sans serif?” My brain went short for a while, until I realized that I indeed had written something about tex fonts previously and maybe the answer was there. It’s the first time I had recognized how useful these shits were to me.. (Honestly I have to admit that after finishing those posts I regretted wasting time on writing nothing useful at all.) So, anyways, I put some of these posts back in this blog.

PS: The answer to the above question of changing to sans serif fonts is a simply line of code:

\renewcommand{\rmdefault}{cmss}

### TeX Fonts (III): postscript

In TeX, a font requires two definition/description files: a metric definition file (.tfm) as introduced in the previous post, and a glyph shape description file (.gf from METAFONT, .pfa/.pfb for printer fonts, etc). The TeX font metric file *.tfm only specifies the dimensions of each character in the font, as well as a list of kerning and ligature pairs. It does not tell how actually a character looks like. The shapes of the characters are only described in the glyph file. The output of a TeX file, *.dvi, merely contains information about a large number of bounding boxes and their relative positions. Hence, in order to print the document to paper or to screen, a dvi file has to be interpreted using a dvi driver with glyph definition in mind. dvips is one such driver. It converts a dvi file to a PostScript file. Yap, or xdvi, or other dvi previewers, are essentially dvi drivers. They assume glyph information, otherwise they have no way of rendering the fonts stored in *.dvi.

Indeed, a large part of fonts talked about in this post are no longer TeX fonts. TeX only recognizes fonts from .tfm files—bounding boxes and kerning informations. METAFONT can produce glyph files (.gf), but fonts we commonly used today are Adobe fonts (.afm), TrueType fonts (.ttf), etc. Corresponding tools are designed to convert these fonts into TeX font metrics, such as afm2tfm, ttf2tfm, recognized by the latex program, as well as into glyph files (ttf2pk, etc) used by the dvi drivers (dvips, Yap, xdvi, etc). The relationships are illustrated in the following figure. (I slightly cheat in the figure in that the Adobe font metric .afm will only be converted to TeX font metric .tfm, but no information is deduced for glyph file.)

[To be finished..]

### TeX Fonts (II): fd, def, and tfm

When we compile a TeX source, such as using “latex helloworld.tex”, the latex program searches for the font definition file ‹enc›‹family›.fd according to the font encoding and family specification inside the LaTeX source, loads the encoding definition ‹enc›enc.def, and typesets each individual character by consulting the TeX font metric file ‹family›[‹size›].tfm. These three files are key to generating the output dvi file.

The font definition file ‹enc›‹family›.fd simply declares the existence of some font, and provides a pointer to the metric file that the latex program should consult when typesetting the document. For example, in the txfont package, which provides characters in the Adobe Times font for both texts and formulas, there is one file t1txr.fd defining the txr font family using T1 encoding. The second and third commands read:

 \DeclareFontFamily{T1}{txr}{} \DeclareFontShape{T1}{txr}{m}{n}{t1xr}{}

It essentially says that a txr font with T1 encoding is defined. Whenever a T1 txr medium normal font is requested, LaTeX should use the t1xr.tfm metric file for all font sizes ( means “for all sizes”).

The corresponding encoding definition file ‹enc›enc.def defines the encoding. Let us see an example first to have an idea about what “encoding” means. In t1enc.def, there are four lines saying:

 \DeclareFontEncoding{T1}{}{} \DeclareTextAccent{\'}{T1}{1} \DeclareTextSymbol{\ae}{T1}{230} \DeclareTextComposite{\"}{T1}{a}{228}

The first line declares the existence of T1 encoding. The following lines mean that when this encoding is in effect the \'{x} command should superimpose character 1 (accent acute) over the character x, that \ae should produce character 230 (the æ ligature), and that \"a should produce character 228 (the umlaut ä). It would be much clearer to compare the above three commands with the corresponding ones in OT1 encoding (ot1enc.def):

 \DeclareTextAccent{\'}{OT1}{19} \DeclareTextSymbol{\ae}{OT1}{26} (no composite command \"a defined)

One can see that, under different encodings, the same character has different indices in the character table. The same command can be issued to reference the same character, while it’s also possible that some characters exist in one encoding but not in the other. The encoding defined in LY1enc.def used by Y&Y TeX systems allows access to all the characters in a standard Adobe roman font.

Finally, the TeX font metric file ‹family›[‹size›].tfm is a binary file that defines width, depth, and height of each character, as well as the kerning pairs and ligature substitutions to be used with the font. LaTeX consults the tfm file to decide where to put characters when typesetting. The tfm file name has an optional [‹size›] field. For example, the cmr family has metric files cmr5.tfm, cmr6.tfm, cmr7.tfm, cmr8.tfm, cmr8.tfm, cmr10.tfm, cmr12.tfm, and cmr17.tfm. Each file fine tunes the size of each character and is used when different font sizes are correspondingly declared.

To summarize, when typesetting the document, latex requires three important files to get the correct encoding and character size information. Latex computes the locations of each character and outputs the dvi file.

• 246,614 hits