OR/MS Today - June 2006



Software Review


MATLAB

Software answers needs of users involved in numerical and symbolic analysis.

By Manuel Tarrazo


MATLAB stands for MATrix-LABoratory. It started as a utility to facilitate access to high-performance linear, algebraic, numerical analysis software, which is essential in many areas of science and practically all areas of business analysis. In the late 1970s, Cleve Moler used Fortran and portions of LINPAK (linear systems package) and EISPACK (eigenvalues package) to develop the first version of MATLAB, primarily because he "wanted students to be able to use the new packages without using Fortran programs" [1]. He and two others founded The MathWorks in 1984 to commercialize MATLAB.

The MathWorks now offers a very complex array of products to meet professional and scientific needs in both academia and industry, which are organized around two main products, MATLAB and Simulink. Each of these products can be purchased separately, and a number of "toolboxes" and "blocksets" complement or extend each of them. The MATLAB "family" includes toolboxes in specialized areas (distributed computing, finance, bioinformatics, fuzzy logic, control, signal processing and communications) and clusters of procedures (optimization, symbolic analysis, partial differential equations, genetic algorithms and direct search, statistics and data analysis, neural networks, splines, curve fitting, GARCH, wavelet, filter design, etc.). This family also includes a number of utilities (links for EXCEL, image acquisition, data acquisition, instrument control, datafeed, database, compiler, report generator, etc.). Modeling needs are addressed by Simulink and related products. (See the "Products" section on The MathWorks site: www.mathworks.com.) There are also more than 300 third-party products available in the United States and many other countries, as shown on The MathWorks Web site: www.mathworks.com/products/connections/product_name.html.

My Purchase of MATLAB


About three years ago, despite my experience with econometrics software (RATS, TSP, GAUSS), programming languages (several varieties of BASIC, Fortran, C) and business software (EXCEL among others), I found myself in need of a tool with which I could enhance my research. My research efforts are on the border between qualitative and quantitative analysis in financial planning and portfolio selection problems; think, for example, of the way you manage your retirement account, or how retirees you know evaluate financial and insurance products. I also study the application of combinatorial and integer optimization, and approximate equations, to portfolio optimization. My Ph.D. training was in econometrics, but now I hardly ever need high-end hypothesis testing statistical software.

In March 2004 I purchased the following products from The MathWorks: MATLAB (Release 13), EXCEL Link, Extended Symbolic Toolbox and Neural Networks Toolbox. One year after my purchase, The MathWorks sent me a maintenance bill that enables me to receive updates for another year. I must confess that I have not used the EXCEL link or the Neural Toolbox, mainly for lack of time. I also have yet to install the Release 14 of the MATLAB because it will not work in the Windows ME desktop I still use at home.

Using MATLAB


My interest in mathematical software was equally focused on both numerical and symbolic analysis. Symbolic analysis is the current "big thing" in mathematical pedagogy. The symbolic toolboxes accompanying MATLAB provide access to MAPLE's analytical kernel, which has the capability to perform symbolic "calculus, transforms, linear algebra, simplification of symbolic expressions, equation solving, specialized mathematical functions, general symbolic operations and variable precision arithmetic" [2]. The Extended Symbolic Toolbox also offers C code, Fortran and LaTex representation of symbolic expressions and full access to the most recent Maple kernel (except for graphics). This means support for programming in Maple and access to Maple specialized mathematics libraries.

Clicking on the MATLAB's desktop icon opens a window with three clearly defined spaces and a menu. There is a "Command Window," which is an interpreter that parses single line instructions or groups of instructions collected in "script" files (known as "batch" files in other programming environments). There is also a "Work Space" and a "Command History." The Work Space shows the names of the variables and memory characteristics; one can access a matrix editor by clicking on its name. As should be expected, matrix manipulation in MATLAB is very easy. I can select a column in A, say the third, by simply typing A(:,3). The Command History window also allows highlight-and-execute for previous commands, command blocks and easy copy-by-dragging. The up-arrow-key rewrites previous commands. The Help Command is also very well designed and includes access to the text in the manuals, as well as numerous examples and demos.

One can work directly with the interpreter (Command Window) or type the name of a script file. To create objects (variables, matrices, functions, expressions, etc.) with MATLAB is easier than with any programming language I have ever used. In programming, one usually has some data that must be processed in a certain way (functions) to obtain a given output which, in turn, is represented in a numerical or a graphical way. Single line functions can be defined in the Command Window with expressions, anonymous and inline functions. Multiline functions reside in external files named after the function. When the function is called, it does its job and its output appears in the Work Space ready for further use. Global variables can be used to change the way the function works.

Examples of MATLAB programs


MATLAB users must choose between the symbolic analysis path and the purely numerical one. Let us see some examples. The MathWorks Web site contains the manuals and many examples. The "Support" area of The MathWorks site contains a link to further specialized examples ("Index of Examples"); these examples can also be accessed through the pages for documentation in the manuals ("Documentation"). In addition, through the "Industry" link, one can access demos on how MATLAB is applied to specific problems in different industries.

Program 1: common procedures. This program illustrates different ways to get something fundamental done: 1) create a variable, 2) assign some values to it, 3) make this variable determine the values of a second variable, and 4) graph them both. Version A is straightforward; Version B, C, D use the symbolic function plotter ezplot(). The output from this program is omitted to optimize space.

review of MATLAB

Program 2: symbolic equation solver. This solver can be applied to both linear and nonlinear equations.

review of MATLAB

review of MATLAB

Figure 1: Graphical output from Program 2.

Program 3: symbolic toolbox and simultaneous differential equations (first order, non-homogenous, Cauchy's problem). Version A shows the "automatic" way of doing it; that is, with the analytic differential equations solver: dsolve.

review of MATLAB

Program 4: textbook version of the tangent portfolio. Given a variance-covariance matrix, and a vector of returns, the tangent portfolio is the grouping of securities that maximizes the returns-to-standard-deviation ratio. The program could be easily modified to calculate means and variance-covariance from a comma-delimited data file. This program shows the convenience and reusability of MATLAB code: once the script is completed it will work every time for any problem dimension. There is no need of further variable declarations or re-dimensioning. The output below is self-explanatory.

review of MATLAB

Program 5: symbolic solver and simultaneous equations system. The same portfolio optimization problem using a set of simultaneous equations is now processed analytically. The solutions below are the optimal portfolio weights in rational numbers. These and the other similar programs below showcase, first, the ability MATLAB has to process information as we often do on blackboards, research papers and textbooks, that is, symbolically. Second, the decimal representation of numbers is replaced by their rational expression, which paves the way to studying issues concerning numerical accuracy.

review of MATLAB

Program 6: Portfolio optimization using fminsearch(). This program uses a general purpose minimization function to compute optimal weights (output not printed). Using a slightly different syntax, fminsearch ('lopt_fun1', xinit), would work as well. To compute optimal weights using fminsearch() is a two-step process. First, we must write an external function and save it in the active directory in MATLAB. Second, we must write the code to invoke fminsearch() itself. The two pieces seem rather straightforward once the two pieces are completed and in working order, but learning how to do it could definitely be more user-friendly. Note that the variance-covariance matrix and the vector of returns are declared "global" variables, which saves us from rewriting the function for different problems, or from passing values each time the function is called. I was disappointed that MATLAB does not include more optimization functions. The procedures included in the Optimization Toolbox are probably state-of-the-art and should be employed in professional and research endeavors. Still, there is ground between those professional-grade functions and fminsearch() that general users of MATLAB may like to see covered by general purpose functions.

review of MATLAB

Program 7: surface chart. Here we present the code for plotting a straightforward 3D (surface) chart in MATLAB (Figure 2). The MATLAB meshgrid() function is similar to the data-table needed in Excel to create surface charts. This program shows the ease of creating graphics with MATLAB. This program could be used to study the portfolio variance, which is a quadratic form.

review of MATLAB

review of MATLAB

Figure 2: Graphical output from Program 7 (surface chart).

Comments, Recommendations and Suggestions


In addition to the characteristics previously noted, the examples programs we have presented stress the following aspects of MATLAB:

First, MATLAB shows a clear preference for working with text files. All scripts and functions are written as text. This strategy makes file sharing easy and links MATLAB code to other text-based programming environments. An alternative strategy, followed by at least one MATLAB competitor, is to use graphic-based editors requiring a proprietary reader and converters. Using Microsoft Word is an option in both MATLAB and its competitor, but it needs to be "handled with care." For example, I often write notes, save pieces of code, output and graphics in a Word file, but copying MATLAB text code into a Word file usually triggers autocorrect actions that disable the code. This especially affects quotation signs.

Second, default MATLAB graphics, as the surface chart shows, tend to be uncomplicated, elegant and direct. Moreover, graphical output appears in a graphics editor that gives users complete control over the output.

Third, learning MATLAB is a complex endeavor. In my experience, the major difficulties stem from the following factors:

  • Different versions of the program require different syntax, which limits the usefulness of the code found in older textbooks. Also, the program itself is evolving. For example, current versions emphasize function handles and anonymous functions and discourage the use of inline functions.

  • MATLAB syntax is sometimes hard to figure out. Some things often seem to work well despite not following the recommended syntax, but this is without guarantees. The error messages sometimes relate to something different from what is going on; for example, typing 'dy" in: dsolve('Dy = a*y'). Some others things are hard to get used to. For example, the anonymous function still looks like an odd construct to me, and I am still trying to figure out what the difference between the "abstract" and "symbolic" functions mentioned in the first page of the User Manual is.

  • It pays to learn the set of reserved words in MATLAB. I have read warnings about working with the "usual indexing suspects," i and j, but have not had problems using them. However, using "C" produced some error statements. Then I read on The MathWorks Web site that "This is a bug in Symbolic Math Toolbox 2.1.3 (R13) in the way the Symbolic Math Toolbox handles 'C' as a variable name. As a workaround, avoid using 'C' as a variable name." I also had problems using the word "try" as file names or variable names. The reason is that "try ... end" is a handy way to input blocks of commands and "trying them out" in MATLAB before having to work with an external script file. For example, 1) copy the entire block of commands in one of the sample files; 2) type "try" in the command window; 3) paste the block of self-contained code; finally, 4) type "end" to execute what was placed between "try" and "end". MATLAB does not like hyphens in script and function filenames (e.g. file-n1.m).

  • The use of quotes, however, is perhaps the trickiest part of all. As Hunt et al put it, "The use of strings and symbolic expressions is often quite subtle and can trip up even experienced users" [3, p.30]. See also their discussion concerning how MATLAB handles expressions, functions and strings [3, p. 107].

  • A positive for MATLAB, that it can be used in different ways, may also be a source of what Cooper calls "perplexing errors" ([4], see his discussion on converting from one class into another, p. 271). The remedy, in our opinion, is to solve (at least at first) the same problem in different ways, until one knows what exactly the program will do.

Concerning syntax, it is good to keep in mind that the reason we purchase specialized tools in the first place is because the problems we are studying are complicated (e.g., variable coefficients, non-homogeneous differential equations). Taking care of using the correct syntax is also a way to save us a great deal of aggravation and time wasted.

Fourth, the MATLAB documentation and examples are quite satisfactory. The help facility is well designed and easy to navigate. There are also efficient utilities to manage the work to be done: the diary; editors for files, graphics, vectors and matrices; a code checker and profiler; and the possibility of using M-books, which enable MATLAB to be used from within Microsoft Word.

Overall, I am very satisfied with my purchase of MATLAB. It does not relieve me from knowing my field, and MATLAB will not write papers for me. But it is a good workhorse to try out things in the best conditions, and there seems to be no better tool for venturing in complex areas of learning, where traditional textbooks and problem-solvers are no longer enough.

Where to But It

MATLAB is available from The MathWorks
3 Apple Hill Drive
Natick, MA 01560
Phone: 508-647-7000
Fax: 508-647-7001
E-mail: info@mathworks.com
Web site: www.mathworks.com

Pricing information:
Pricing starts at $1,900 for an individual commercial MATLAB license and $500 for an individual academic MATLAB license. Prices of add-on products vary. Contact The MathWorks for further information on pricing and license options (www.mathworks.com).





Manuel Tarrazo is an associate professor of finance at the School of Business & Management, University of San Francisco.

References


  1. Moler, Cleve, 2004, "The Origins of MATLAB," also available on video.
  2. www.mathworks.com/products/extsymbolic/description1.html.
  3. Hunt, B., Lipsman, R., Osborn, J. and Rosenberg, J., 2005, "Differential Equations with MATLAB," Wiley.
  4. Cooper, J., 2001, "A MATLAB Companion for Multivariate Calculus," Hardcourt/Academic Press.





  • Table of Contents
  • OR/MS Today Home Page


    OR/MS Today copyright © 2006 by the Institute for Operations Research and the Management Sciences. All rights reserved.


    Lionheart Publishing, Inc.
    506 Roswell Rd., Suite 220, Marietta, GA 30060 USA
    Phone: 770-431-0867 | Fax: 770-432-6969
    E-mail: lpi@lionhrtpub.com
    URL: http://www.lionhrtpub.com


    Web Site © Copyright 2006 by Lionheart Publishing, Inc. All rights reserved.