Elements of MATLAB Style

140415-1443-12-4032-cropped.jpg

Style is an important aspect of writing, and also of programming. While MATLAB is a quick and easy language in which to program, style should not be neglected. Good style aids readability, which in turn makes it easier to debug and maintain code. It also fosters confidence in the code. Here are six style tips, in which the examples given are all inspired by real-life code that I have come across.

For more on MATLAB style see the book MATLAB Guide, and in particular section 16.1, “Elements of Coding Style”.

1. Omit Unnecessary Parentheses

% Bad style.
x = (A')\b;
y = [1];
D = (diag(x));

The parentheses around A' are unnecessary. Without them, the statement is legal and unambiguous. But of course the parentheses would be necessary in, for example, x = (A*B)'\c;

y is a scalar. There is no need to enter it as a 1-by-1 matrix by putting it in square brackets.

There is no need for parentheses around the diag function.

% Good style.
x = A'\b;
y = 1;
D = diag(x);

2. Use Spaces Consistently

% Bad style.
q=sqrt(2);
a = 1;
Z =zeros(3);
for i=1:10, q=q+1/q; end

Stick to a convention about spacing around around equals signs and plus and minus signs. I think spaces make the code more readable.

% Good style.
q = sqrt(2);
a = 1;
Z = zeros(3);
for i = 1:10, q = q + 1/q; end

3. Omit Unnecessary Semicolons and Commas

% Bad style.
figure;
for i = 2:n,
    x(i) = x(i-1)^2*y(i);
end;

Semicolons suppress output, but in this example there is no need for the them since no output is returned by the figure or end functions. The comma would only be necessary if the for loop was collapsed onto one line.

% Good style.
figure
for i = 2:n
    x(i) = x(i-1)^2*y(i);
end

4. Use the Appropriate Construct

The following if statement is perfectly correct.

% Bad style.
if flag == 1
   fprintf('Failed to converge.\n')
elseif flag == 2
   fprintf('Overflow encountered.\n')
elseif flag == 3
   fprintf('Division by zero.\n')
elseif flag == 4
   fprintf('Tolerance too small.\n')
end

But given its regular structure, it is better written as a switch statement, which is shorter, brings out the parallelism in the logic, and is easier to check.

% Good style.
switch flag
   case 1, fprintf('Failed to converge.\n')
   case 2, fprintf('Overflow encountered.\n')
   case 3, fprintf('Division by zero.\n')
   case 4, fprintf('Tolerance too small.\n')
end

5. Omit Trailing Tildes

In the list of output arguments in a function call a tilde signifies that the output argument in that position is not wanted and so can be discarded (and hence need not be computed). This notation was introduced in MATLAB R2009b. Generally, there is no point in providing a tilde as the last output argument, as a well written function will check the number of requested outputs and not compute any trailing outputs that are not requested.

The singular value decomposition (SVD) of a matrix A is computed by the call [U,S,V] = svd(A). In the following example we wish to compute the left singular vectors of A but not the singular values or right singular vectors.

% Bad style.
[U,~,~] = svd(A);

% Good style
[U,~] = svd(A);

An obvious question is why the second example was not shortened to

U = svd(A);

The reason is that with one output argument the svd function has a special behavior: it returns a matrix of singular values, not the matrix U of left singular vectors.

6. Include an H1 line in Program Files

The H1 line in a MATLAB program file is a comment line that is the second line in the file and contains the program name followed by a one-line description of the program. It is good practice to provide every program with an H1 line, as MATLAB itself does. Several MATLAB functions make use of H1 lines. For example, when the help function is invoked with a directory name and the directory in question does not contain a contents.m file, a list of contents is created from the H1 lines of the program files in the directory and displayed.

Here is an example of a function with an H1-line (this is an updated version of a function from The Matrix Computation Toolbox).

function show(x)
%SHOW   Display signs of matrix elements.
%   SHOW(X) displays X in `FORMAT +' form, that is,
%   with `+', `-' and  blank representing positive, negative
%   and zero elements respectively.

f = get(0,'Format'); % Get current numerical format.
format +
disp(x)
format(f)            % Restore original numeric format.
Posted in software | Tagged | 2 Comments

How to Print a Page Across Multiple Pages with Adobe Acrobat

Occasionally I need to proof a PDF document that is too small to read comfortably when printed in the usual way. This is the case with my columns for SIAM News, as SIAM News is A3 format whereas my printer is A4.` ‘ A simple solution is to use the Poster option under “Page Size & Handling” in Adobe Acrobat’s print dialog box. Acrobat will print each page over multiple pages that, if joined together, reproduce the original pages (except for the white margins). The preview window in the dialog box shows how each page will be split into pieces. You can adjust the percentage in the “Tile Scale” box to increase or decrease the number of printed pages per original page.

acrobat-poster.jpg

(This screen capture shows Adobe Acrobat version 11.0.19; the dialog box may be different in other versions of Acrobat.)

Here is a photograph of the result laid out on my office floor, with the four A4 sheets arranged to match the original document. (This is the proofs of my April 2017 SIAM News column.)

170317-0952-56-6777.jpg

This Poster option is no doubt particularly intended for proofing posters on an A4 or A3 printer, as they are typically designed for printing at A0 or A1.

You may notice that in the screen capture above my printer is Fineprint. This is an application that acts as a Windows printer driver and captures and displays what is printed to it, possibly from multiple print commands. It allows the user to reorder, magnify (via the “Enlarge” option), and edit pages before actually printing them, and printing can be 1-up, 2-up, 4-up, or 8-up. I have been using FinePrint for many years and could not live without it. It saves me paper and by allowing me to reduce the margins makes documents much easier to read. The following screen capture shows FinePrint after printing the document shown above with the Poster option at 120%.

fineprint-ex.jpg

Posted in software | Tagged , | Leave a comment

What’s New in MATLAB R2017a?

MATLAB R2017a was released last week. Many of the changes reported in the release notes are evolutionary, building on and extending major new features introduced previously. For example, the Live Editor continues to gain expanded capabilities. In this post I pick out a few new features that caught my eye. This is very much a personal selection. For full details of what’s new, see the release notes, and see also my previous post What’s New in MATLAB R2016b if you are not familiar with R2016b.

Parula

The parula color map has been modified slightly. The difference is subtle, but as the following example illustrates, the R2017a parula is a bit more vibrant and has a bit less cyan and yellow in the blues and greens.

parula-2016b-2017a.jpg

I note, however, that the difference between the old and the new parula is smaller when the images are converted to the CMYK color space, as they must be for printing.

Heatmap

The new heatmap function plots a heatmap of tabular data. Although it is intended mainly for use with the table data type, I think heatmap will be useful for getting insight into the structure of matrices, as illustrated by the following examples.

heatmaps.jpg

String Arrays

String arrays, introduced in MATLAB R2016b, can now be formed using double quotes:

>> s = string('This is a string') % R2016b
s = 
    "This is a string"
>> t = "This is a string"         % R2017a
t = 
    "This is a string"
>> isequal(s,t)
ans =
  logical
   1
>> whos
  Name      Size            Bytes  Class     Attributes

  s         1x1               166  string              
  t         1x1               166  string

However, there is one major caveat. Many MATLAB functions that take a char as input argument have not yet been adapted to accept strings. Hence

>> A = gallery('moler',3)
A =
     1    -1    -1
    -1     2     0
    -1     0     3
>> A = gallery("moler",3)
Error using nargin
Argument must be either a character vector or a function handle.
Error in gallery (line 191)
nargs = nargin(matname);

I expect that such functions will be updated in future releases.

Missing

A new function missing creates missing values appropriate to the data type in question.

>> A = ones(2); A(2,2) = missing
A =
     1     1
     1   NaN

> d = datetime('2014-05-26')
d = 
  datetime
   26-May-2014
>> d(2) = missing
d = 
  1×2 datetime array
   26-May-2014   NaT

Until converted to the target datatype, a missing value has class missing:

>> m = missing
m = 
  missing
    
>> class(m)
ans =
    'missing'

Performance Improvements

The release notes report performance improvements under a variety of headings, including execution engine, scripts, and mathematics functions. These are very welcome, as the user automatically benefits from them. One comment that caught my eye is “The backslash command A\B is faster when operating on negative definite matrices”. I think this means that MATLAB checks whether the matrix, A, is symmetric with all negative diagonal elements and, if it is, attempts a Cholesky factorization of -A.

Posted in software | Tagged | Leave a comment

Tracing the Early History of MATLAB Through SIAM News

A recent blog post by Ned Gulley points out that the new mathematics gallery (“Mathematics: The Winton Gallery”) at the Science Museum, London, contains a copy of the disk and manual for MATLAB 1.3, from 1985, sitting next to a trial assembly of Charles Babbage’s analytical engine.

This set me thinking about the early history of MATLAB and The MathWorks. Items such as manuals and disks must be quite rare nowadays. What other traces are there of early MATLAB history? I have recently been looking through some back issues of SIAM News and spotted a number of adverts for MATLAB over the period 1985–1991. Let’s see what historical insight these early adverts give.

1985

sinews-1985-18-2-mathworks_ad.jpg PDF file

The first advert I can find is from the March 1985 SIAM News, and it is for PC-MATLAB, priced at $695, running on an IBM-PC or compatible computer. The advert features the now famous MathWorks logo, which represents an eigenfunction of the L-shaped membrane. It quotes a time of 10.1 seconds for a 50-by-50 real matrix multiplication on a machine with an Intel 8087 coprocessor. This floating-point coprocessor was a useful add-on to the IBM-PC, which used the Intel 8086 chip.

MATLAB benefited from being launched at a time when the IBM PC with 8087 coprocessor was just starting to become popular. The 8086-8087 combination made it possible to carry out computations on a desktop PC that had previously required a minicomputer—and they could now be done with the interactive MATLAB interface.

The advert mentions “mainframe MATLAB”, which it says is written in Fortran, runs on “larger computers”, and is in use in several hundred organizations worldwide.

PC-MATLAB had been rewritten in C, and it supported graphics, IEEE arithmetic (as implemented in the 8087), and “user-defined functions” (M-files).

Note that at this time MathWorks was located at 124 Foxwood Road, Portola Valley, California. In his article The Growth of MATLAB and The MathWorks Over Two Decades, Cleve Moler explains that this first mailing address was “a rented A-frame cabin where Jack [Little] lived in the hills above Stanford University in Portola Valley, California”.

The September 1985 issue of SIAM News contains a rather different advert that now refers to “the original mainframe version of MATLAB” and emphasizes the ease of use of MATLAB.

sinews-1985-18-5-mathworks_ad.jpg PDF file

1987

sinews-1987-20-1-mathworks_ad.jpg PDF file

The next advert is from the January 1987 SIAM News. MATLAB is now also available as Pro-MATLAB running on a Sun workstation or a VAX computer. M-files are now mentioned by that name and LINPACK benchmark figures are stated, the largest figure being 98 Kflops on the MicroVAX II.

The MathWorks has now moved to Massachusetts.

1990

sinews-1990-23-3-mathworks_ad.jpg PDF file

The advert in the May 1990 SIAM News gives a version number, MATLAB 3.5, and it announces the Signal Processing Toolbox. It boasts that MATLAB has over 400 built-in functions and supports an enlarged range of computers, which include Cray supercomputers. The benchmark for a 50-by-50 real matrix multiplication is now down to 0.71 seconds on a 20 Mhz 386-based PC: a reduction by a factor of 14 from the figure quoted in 1985.

A strange feature of the advert is that the toolbox is only explicitly mentioned in the box at top left and the meaning of “toolbox” is not stated.

The MathWorks address has changed again, to 21 Eliot St., South Natick, Massachusetts. In the article mentioned above, Cleve explains, “When the company reached about a dozen employees, we moved several miles east to take over the second floor of a lovely building in South Natick, Massachusetts”.

1991

sinews-1991-24-5-mathworks_ad.jpg PDF file

The advert in the May 1991 issue of SIAM News focuses on two new toolboxes: the Spline Toolbox and the Optimization Toolbox. The gray box defines toolboxes as “sets of routines written in the MATLAB programming language for specialized applications”.

MathWorks is now located at Cochituate Place on Prime Park Way in Natick. The street was so-named because it had been the home of the Prime Computer Corporation, which produced minicomputers from 1972 to 1992.

These adverts give some insight into the development of MATLAB in its early years. They also show how the rapid growth of MathWorks necessitated frequent relocation of the company. Indeed, in the article mentioned above Cleve Moler notes that the number of employees roughly doubled every year for the first seven years.

Posted in software | Tagged , | Leave a comment

Parallel Numerical Linear Algebra for Extreme Scale Systems

A minisymposium Parallel Numerical Linear Algebra for Extreme Scale Systems was held at the SIAM Conference on Computational Science and Engineering, Atlanta on February 28, 2017.

170228-0921-02-5781.jpg

Jack Dongarra.

Today’s most powerful supercomputers are composed of hundreds of thousands of computing cores (CPUs and accelerators) connected in high speed networks that make up a massively parallel high performance computing (HPC) system. These systems are placing new demands on effective scalable numerical algorithms and software libraries, which will only increase in the future as we move towards increasingly heterogeneous systems with millions of compute cores. This minisymposium, which I organized jointly with Bo Kågström (Umeå University, Sweden), focused on addressing these challenges in the context of linear algebra problems through developing novel parallel algorithms, exploring advanced scheduling strategies and runtime systems, carrying out offline and online autotuning, and avoiding communication and synchronization bottlenecks.

170228-1020-54-5783.jpg

Iain Duff showing the new second edition of Direct Methods for Sparse Matrices.

The speakers were all members of the NLAFET (Parallel Numerical Linear Algebra for Future Extreme-Scale Systems) project, which is one of the high-profile extreme-scale computing research projects funded by the European Commission within the Future and Emerging Technologies (FET) program under Horizon 2020. Much of the work described in the minisymposium was carried out within NLAFET.

Around 75 people attended and there was standing room only. Here are the talks, with links to the slides. The names of the speakers are italicized.

Related to this minisymposium was the two-day Workshop on Batched, Reproducible, and Reduced Precision BLAS, held a couple of days beforehand at Georgia Tech. The workshop included presentations from both academia and industry and the program contains links to the speakers’ slides.

Posted in conferences | Tagged | Leave a comment

Writing Mathematics in Pencil, and Why Analogue is Not Dead

It’s an old joke that mathematicians need just a pencil, paper, and a bin, while philosophers are even more frugal because they don’t need the bin. Yet nowadays more and more of the time of mathematicians, indeed all scientists, is spent at the computer. Whereas twenty years ago I would handwrite a draft of a paper before typing it in, I now do almost all the drafting directly in \LaTeX at the keyboard.

But in response to computers dominating our lives, and in a move away from the (mythical?) paperless office, people are increasingly reverting to analogue tools, encouraged by the pleasure of handling stationery and, for those of us who were brought up in an analogue world, nostalgia.

This is a good time to employ retro tools in a digital world because we can now buy online an increasingly wide variety of stationery from all around the world.

What might you gain by writing mathematics with a pencil and paper as opposed to typing it at the computer? Sitting at a desk with a pencil in hand you are free from the distractions of the windows on your computer screen. The analogue process, with its delays of turning a page, sharpening the pencil, and rubbing out mistakes, has the benefit of slowing you down and thereby promoting your flow of thought and creativity. And the touch of the paper and the smell of cedar as you sharpen the pencil refresh the senses.

161209-2045-01-5702-cropped.jpg

CW Pencil Enterprise, New York, “purveyor of superior graphite, etc.”

Donald Knuth has another reason for writing with a pencil, as explained in this 2008 interview.

I love keyboards, but my manuscripts are always handwritten. The reason is that I type faster than I think. There’s a synchronization problem. I can think of ideas at about the rate I can write them down with a pencil. But with typing I’m going faster, so I have to sync, and my thoughts have to start up and stop again in a way that involves more of my brain.

Yet more reasons for using pencils are given in the video Why Use Pencils? by T. J. Cosgrove. One of T. J.’s points is that the graphite produced by a pencil does not fade, unlike inks.

It is also worth noting that in some recently published research psychologists found evidence that students who take notes with pencil (or pen) and paper outperform those who take notes on a laptop.

So there are some good reasons for writing with a pencil. How should you choose one from among the many different types available?

I don’t know of a good source of advice on pencils for mathematicians (maybe I will write something in due course), but this blog post on pencils for musicians is largely applicable if you replace “music” by “mathematics”. The post is by Caitlin Elgin, from the wonderful Manhattan pencil shop pictured in the photo above, which I took when I visited it last year.

Posted in writing | Tagged | 2 Comments

PCAM Authors Speaking About Their Work at SAMSI

The Statistical and Applied Mathematical Sciences Institute (SAMSI) has just run a Workshop on the Interface of Statistics and Optimization. Among the speakers were four authors of articles in The Princeton Companion to Applied Mathematics (PCAM).

In an earlier post I provided links to videos of PCAM authors giving talks related to the topics of their PCAM articles. To add to those, here are the four PCAM author talks from the SAMSI workshop.

I have also included the talk by Margaret Wright, because it provides insight into a number of important topics covered in PCAM in a very lucid way.

  • John Burns, Parameter Identification for Dynamical Systems with Structured Uncertainty (author of PCAM article Optimal Sensor Location in the Control of Energy-Efficient Buildings)

  • Jack Dongarra, The Road to Exascale and Legacy Software for Dense Linear Algebra (author of PCAM article High-Performance Computing)

  • Yonina Eldar, Phase Retrieval and Analog to Digital Compression (author of PCAM article Compressed Sensing)

  • Stephen Wright, Randomness in Coordinate Descent (author of PCAM article Continuous Optimization (Nonlinear and Linear Programming)

  • Margaret Wright, Old, New, Borrowed, and Blue in the Marriage of Statistics and Optimization

Posted in Princeton Companion | Tagged , | Leave a comment

Preparing CMYK Figures for Book Printing

All printing is done in CMYK, the color space based on the four colors cyan, magenta, yellow, and black. Figures that we generate in MATLAB and other systems are invariably saved in RGB format (red, green, blue). When we send a paper for publication we submit RGB figures and they are transformed to CMYK somewhere in the production process, usually without us realizing that it has been done.

If you are one of those people who writes books and prefers to generate the final PDF yourself then you will need to convert any color figures to CMYK. The generation and use of CMYK files is something of a dark art. Here I report what I found out about it when producing the third edition (2017) of MATLAB Guide, co-authored with Des Higham. This is the first edition of the book to use color.

CMYK produces a different range of colors than RGB. Since it is a subtractive color space, designed for inks, it cannot produce some of the brilliant colors that RGB can, especially in the blues. In other words, some RGB colors are out of gamut in CMYK. (Less importantly, the converse is true: some CMYK colors cannot be produced in RGB.) This is something we are used to, but usually do not notice. Whenever we print a document on a laser printer we view a CMYK representation of the colors. In many cases, a figure will look very similar in print and on screen, but there are plenty of exceptions.

The following image shows an RGB image on the left, the result of converting that image to CMYK and then back to RGB in the middle, and a scan of a laser printer’s reproduction of the RGB image on the right. circle-rgb-cmyk-scan.jpg The differences between the RGB version and the other two versions may be shocking! Fortunately, when the CMYK version is viewed on a printed page in isolation from the RGB version (necessarily displayed on a monitor) it does not look so bad. [Of course, if you are reading a printed version of this post then the first two images will look essentially the same.]

After some experimentation, I settled on the following procedure, which I describe for a PDF workflow. For a PostScript workflow, PDF files need to be replaced by EPS files.

  • Print the whole document from an RGB file.
  • Find figures that look very different in print than on screen and select from those any where the difference is not acceptable. In most cases an unacceptable difference will be one where contrast between colors, or saturation of colors, has been reduced.
  • Edit the selected figures in Photoshop, or some other image manipulation package that can save in CMYK form, in order to produce a better looking CMYK file. In Photoshop, Image-Mode-CMYK Color converts an image to CMYK form, but before using this command you should set the correct CMYK working space under Edit-Color Settings (see the Color Space section below). You can edit the RGB image (making use of View-Proof Color to see how the image will look in CMYK, and View-Gamut Warning to see colors that will be out of gamut in CMYK) and then convert to CMYK, or you can convert to CMYK and then edit the file. Save the CMYK image as a PDF file.
  • Generate the PDF file of the book using the edited CMYK figures and the RGB forms of all the other figures, that is, those that did not need special treatment.
  • Load the PDF file into Adobe Acrobat Pro and issue the command
    Tools - Print Production - Convert Colors
    

    This converts all objects in the file to CMYK.

Of the well over 100 figures in MATLAB Guide, only two needed special treatment.

However, there was one problem with this procedure. A handful of images are screen dumps that show a MATLAB window, and these are necessarily low resolution, at 72dpi. When converted to CMYK in Adobe Acrobat these images degraded badly. The solution was to resample the images to 150dpi in Photoshop via Image-Image Size and save to PDF; conversion in Acrobat then worked fine. (Such resampling is probably good practice anyway.)

This is not quite the full story. Here are some more gory details, which are worth reading if you are actually producing a book.

Color Spaces

There is no unique CMYK or RGB color space: these spaces are device dependent. RGB spaces can have different white points and CMYK spaces are designed for particular combinations of paper and ink. Adobe Acrobat Pro offers “U.S. Web Coated (SWOP) v2”, “Uncoated FOGRA29 (ISO 12647-2:2004)” and many other inscrutably named CMYK profiles. So “convert to CMYK” is an ill-defined instruction unless the precise profile is specified. The conversion settings I used are shown in this screen dump of the dialog box, and were provided by the company who printed the book. Your settings might need to be different. acrobat-cymk-conversion.jpg There are a couple of things to note. First, Adobe Acrobat does not remember the settings in the dialog box, so they need to be re-entered every time. Second, since “Embed profile” is not selected with the settings shown, there is no way to tell which profile has been used once the conversion has been done.

Does it really matter what CMYK profile you use? Yes, if you want the best possible results. Consider the following figure. circle-rgb_cmtk-2convs.jpg On the left is the result of converting the original RGB image to “U.S. Web Coated (SWOP) v2” and on the right is the result of converting to “Photoshop 5 default CMYK” (and converting back to RGB in both cases, the latter conversion producing no visual difference in Photoshop). There is a significant difference between the two conversions in every color except white! In principle, both conversions will produce the same result when printed with the target ink and paper, but if you choose the profile without knowing the target you have little idea what the printed result will be.

Photography Books

An important assumption in the process described above is that the accuracy of the color reproduction is not vital. For photography books this assumption clearly does not hold and conversion to CMYK enters a new and frightening realm where images might need to be individually fine-tuned. Indeed high quality photography books typically undergo one or more proof stages using actual galley proofs from the ultimate printing device, sometimes with the author present at the printing press.

Generating CMYK Files in MATLAB

Most of the figures in MATLAB Guide are (naturally) produced in MATLAB. Figures saved with the print function are by default in RGB mode. CMYK is supported for EPS and PS files only, using the ‘-cmyk’ option. This is not very useful if you are using a PDF workflow, as I do.

Instead of using the print function I experimented with export_fig, which is available on MathWorks File Exchange and can save in CMYK format to PDF, EPS, or TIFF files. export_fig creates a PDF file via an EPS file using Ghostscript.

This sounds straightforward, but I found that many of the PDF files generated by export_fig were not fully in CMYK Mode. A PDF file can contain objects in different color spaces and I had files where a color plot was in CMYK but the colorbar was in RGB! The question arises of how one can check whether a given PDF file has any RGB objects. Unfortunately, there seems to be no simple way to do so in Adobe Acrobat Pro. What one can do is invoke

Tools - Print Production - Preflight - PDF analysis - 
List objects using ICCbased CMYK - Analyze

then open up

Overview - color spaces

(I am using Adobe Acrobat Pro XI, 11.0.18; usage could differ in other versions). This should contain “DeviceCMYK color space”, but if it contains “DeviceRGB color space” or “DeviceGray color space” then RGB or Grayscale objects are present. If the latter terms appear in a multi-page PDF file, double clicking on the corresponding icon should take you to the last such object.

You can also open up

Overview - Images

to get a list of pages and object types on those pages. Double clicking on a page icon takes you to that page.

Posted in books | Tagged , | Leave a comment

Good Times in MATLAB: How to Typeset the Multiplication Symbol

The MATLAB output

>> A = rand(2); whos
  Name      Size            Bytes  Class     Attributes

  A         2x2                32  double

will be familiar to seasoned users. Consider this, however, from MATLAB R2016b:

>> s = string({'One','Two'})

s = 
  1×2 string array
    "One"    "Two"

At first sight, you might not spot anything unusual, other than the new string datatype. But there are two differences. First, MATLAB prints a header giving the type and size of the array. It does so for arrays of type other than double precision and char. Second, the times symbol is no longer an “x” but is now a multiplication symbol: “×”.

The new “times” certainly looks better. There are still remnants of “x”, for example in whos s for the example above, but I presume that all occurrences of “x” will be changed to the new symbol in the next release

However, there is a catch: the “×” symbol is a Unicode character, so it will not print correctly when you include the output in LaTeX (at least with the version provided in TeX Live 2016). Moreover, it may not even save correctly if your editor is not set up for Unicode characters.

Here is how we dealt with the problem in the third edition (published in January 2017) of MATLAB Guide. We put the code

\usepackage[utf8x]{inputenc}
\DeclareUnicodeCharacter{0215}{\ensuremath{\times}}

in the preamble of the master TeX file, do.tex. We also told our editor, Emacs, to use a UTF-8 coding, by putting the following code at the end of each included .tex file (we have one file per chapter):

%%% Local Variables:
%%% coding: utf-8
%%% mode: latex
%%% TeX-master: "do"
%%% End:

With this setup we can cut and paste output including “×” into our .tex files and it appears as expected in the LaTeX output.

Posted in LaTeX, software | Tagged | Leave a comment

Hyphenation of Compound Words

Compound words are common in mathematical writing and it can be hard to remember how to hyphenate them. Unfortunately, there are no hard and fast rules. In this article I give some guidance and illustrative examples. The principle to keep in mind is that hyphenation should help to avoid ambiguity.

In phrases of the form “adjective noun noun” or “noun adjective/participle noun” a hyphen is usually used: closed-form solution, nineteenth-century mathematics, error-correcting code. But if the adjective follows the noun then no hyphen is needed: solution in closed form, mathematics of the nineteenth century, code that is error correcting. Here are some other examples:

  • nearest-neighbor interpolation,
  • higher-dimensional discrete Fourier transforms,
  • large-scale optimization problem,
  • minimum-norm solution but solution of minimum norm,
  • first-order differential equation but differential equation of first order,
  • the parameter-dependent ODE but the ODE is parameter dependent,
  • rank-1 matrix but the matrix has rank 1.

In examples such as finite-difference method and finite-element method it is a matter of convention and taste whether to hyphenate. Some authors do and some don’t. Most authors do not hyphenate singular value decomposition.

Compounds beginning with adverbs ending in ly are not hyphenated, since they are usually unambiguous. Examples: slowly converging sequence, highly oscillatory integrand, continuously differentiable function, numerically oriented examples.

An important special case is compounds beginning with ill, well, little, much, and best, the first two of which are particularly common in mathematical writing. Here, a hyphen is used for a compound of two words used adjectivally, but if the compound itself is modified then no hyphen is used. Examples (these also apply with ill replaced by well):

  • This is an ill-conditioned problem.
  • This is a very ill conditioned problem.
  • The problem is ill conditioned.
  • This problem is very ill conditioned.

If the first example were to be written as This is an ill conditioned problem then it could be read as if ill were an adjective modifying the compound conditioned problem. Confusion is unlikely in this instance, but in ill-prepared contestant the hyphen is needed unless we are talking about a contestant who is prepared but not well.

Here are two further examples that are complete sentences.

  • MATLAB allows a two-dimensional array to be subscripted as though it were one dimensional.
  • This approach is particularly well-suited to high-precision computation.

The hyphen in well-suited in the last example is not essential, but is rather a matter of taste.

I know from personal experience that it is hard to achieve good, consistent hyphenation when you are concentrating on all the other aspects of writing. This is where having the services of a copy editor is extremely valuable. To benefit, you need to publish with a journal or book publisher that takes copy editing seriously (SIAM, PUP, CUP, OUP, …).

I give the final word to an Oxford University Press style manual, as quoted in the Economist Style Guide:

If you take hyphens seriously, you will surely go mad.

I am indebted to Sam Clark of T&T Productions for checking this post (and for saving me from many hyphenation blunders in my last two books).

Posted in writing | Leave a comment