1 General Questions

1.1. General Information

1.1.1. What is MATLAB?

MATLAB was originally developed to be a "matrix laboratory," written to provide easy access to matrix software developed by the LINPACK and EISPACK projects. Since then, the software has evolved into an interactive system and programming language for general scientific and technical computation and visualization. The basic MATLAB data element is a matrix. MATLAB commands are expressed n a form very similar to that used in mathematics and engineering. For instance, b = A x, where A, b, and x are matrices, is written b = A * x. To solve for x in terms of A and b, write x = A\b. There is no need to program matrix operations explicitly like multiplication or inversion. Solving problems in MATLAB is, therefore, generally much quicker than programming in a high-level language such as C or FORTRAN. There are hundreds of built-in functions that come with the basic MATLAB and there are optional "toolboxes" of functions for specific purposes such as Controls, Signal Processing, and Optimization. Most of the functions in MATLAB and the Toolboxes are written in the MATLAB language and the source code is readable. There are two basic versions of the software, the professional version, and the student edition. The student edition is distributed by Prentice-Hall, the professional version is distributed by The MathWorks, Inc. Send an email to info@mathworks.com or call 508-65-pi (508-653-1415) for more information.

1.1.2. What is SIMULINK?

SIMULINK is an interactive system for the nonlinear simulation of dynamic systems. It is a graphical, mouse-driven program that allows systems to be modeled by drawing a block diagram on the screen. It can handle linear, nonlinear, continuous-time, discrete-time, multivariable, and multirate systems. SIMULINK runs on workstations using X-Windows, under Microsoft Windows on the PC, and on the Macintosh. It takes full advantage of windowing technology, including pull-down windows and mouse interactions. SIMULINK is fully integrated with MATLAB, and, together with MATLAB and the Control System Toolbox, forms a complete control system design and analysis environment.

1.1.3. On what machines is MATLAB available?

MATLAB is available on machines ranging from the PC to the Cray. The list includes PC, Macintosh, Power Macintosh, NEC personal computers, Sun, DEC, HP, IBM, and SGI workstations, VAX minicomputers, and Convex and Cray supercomputers.

1.1.4. What was first: the company MathWorks or the product MATLAB?

MATLAB was first. The MathWorks, Inc. was founded in 1984 to develop and market MATLAB.

1.1.5. What is the history of MATLAB?

In the mid-1970s, Cleve Moler and several colleagues developed the FORTRAN subroutine libraries called LINPACK and EISPACK under a grant from the National Science Foundation. LINPACK is a collection of FORTRAN subroutines for solving linear equations, while EISPACK contains subroutines for solving eigenvalue problems. Together, LINPACK and EISPACK represent the state of the art software for matrix computation. In the late 1970s, Cleve, who was then chairman of the computer science department at the University of New Mexico, wanted to be able to teach students in his linear algebra courses using the LINPACK and EISPACK software. However, he didn't want them to have to program in FORTRAN, because this wasn't the purpose of the course. So, as a "hobby" on his own time, he started to write a program that would provide simple interactive access to LINPACK and EISPACK. He named his program MATLAB, for MATrix LABoratory. Over the next several years, when Cleve would visit another university to give a talk, or as a visiting professor, he would end up by leaving a copy of his MATLAB on the university machines. Within a year or two, MATLAB started to catch on by word of mouth within the applied math community as a "cult" phenomena. In early 1983, John Little was exposed to MATLAB because of a visit Cleve made to Stanford University. Little, an engineer, recognized the potential application of MATLAB to engineering applications. So in 1983, Little teamed up with Moler and Steve Bangert to develop a second generation, professional version of MATLAB written in C and integrated with graphics. The MathWorks, Inc. was founded in 1984 to market and continue development of MATLAB.

1.1.6. What is the charter for the USENET Newsgroup comp.soft-sys.matlab?

The newsgroup comp.soft-sys.matlab is a forum for discussing issues related to the use of MATLAB. Appropriate discussion in the group will include both general MATLAB issues and platform-specific questions, and discussions comparing MATLAB to other systems.

1.1.7. Are there any software archives?

The MathWorks maintains an archive on the anonymous ftp server ftp.mathworks.com [144.212.100.10]. This site contains a "best of" copy of the NETLIB archive as well as other user-contributed, and MathWorks-contributed software and documentation. If you are interested in submitting software to the archive, get the file /README.incoming on the ftp site or send email to: drea@mathworks.com.

1.1.8. Are there any publications related to MATLAB?

Yes, The MathWorks Inc. publishes a quarterly newsletter that gives information on products (new versions, releases, toolboxes), the MATLAB user group, MATLAB short courses, related texts etc. There is also a monthly email digest that contains annoncements, Q &A requests from users, news about our Internet services, etc. To subscribe to the newsletter, send email to subscribe@mathworks.com (Be sure to include your address and your site identification/license number. To find out your site id, type "ver" at the MATLAB prompt.), or just type subscribe at your MATLAB prompt.

1.1.9. What toolboxes are currently available from The MathWorks?

* Control System Toolbox. This is a toolbox for control system design and analysis. It supports transfer function and state-space forms (continuous/discrete time, frequency domain), as well as functions for step, impulse, and arbitrary input responses. Functions for Bode, Nyquist, Nichols plots, design with root-locus, pole-placement, and LQR optimal control are also included.

* Image Processing Toolbox. The Image Processing Toolbox builds on MATLAB's numeric, signal processing, and visualization capabilities to provide a comprehensive system for image processing and algorithm development.

* MMLE3 Identification Toolbox. The MMLE3 Identification Toolbox is a specialized toolbox for use with MATLAB and the Control System Toolbox for the estimation of continuous-time state-space models from observed input-output data.

* Model Predictive Control Toolbox. The Model Predictive Control Toolbox is especially useful for applications involving constraints on the manipulated and/or controlled variables. For unconstrained problems, model predictive control is closely related to linear quadratic optimal control, but includes modeling and tuning options that simplify the design procedure.

* Mu-Analysis and Synthesis Toolbox. The Mu-Analysis and Synthesis Toolbox contains specialized tools for the analysis and design of robust, linear control systems, extending MATLAB to provide additional application-specific capabilities.

* Nonlinear Control Design. This toolbox provides a Graphical User Interface to assist in time-domain-based control design. With this toolbox, you can tune parameters within a nonlinear SIMULINK model to meet time-domain performance requirements. You can view the progress of an optimization while it is running. Optimization routines have been taken from the Optimization Toolbox.

* Neural Network Toolbox. This is a toolbox for designing and simulating neural networks and supports implementation of the perceptron learning rule, the Widrow-Hoff rule, and several variations of the backpropagation rule. Transfer functions included are hard limit, linear, logistic, and hypertangent sigmoid.

* Optimization Toolbox. This is a toolbox for linear and nonlinear optimization. It supports unconstrained and constrained minimization, minimax, nonlinear least squares, multi-objective, semi-infinite optimization, linear programming, quadratic programming, and the solution of nonlinear equations.

* Robust Control Toolbox. This is a toolbox for robust control system design and supports LQG/loop transfer recovery, H2, H0, and mu- control synthesis, singular value frequency response, and model reduction.

* Signal Processing Toolbox. This is a toolbox for digital signal processing (time series analysis). It includes functions for the design and analysis of digital filters, like Butterworth, Elliptic, and Parks-McClellan, and for FFT analysis (power spectrum estimation). It also includes some two-dimensional signal processing capabilities.

* Spline Toolbox. This is a toolbox for working with splines and is typically used for curve fitting, solution of function equations, and functional approximation.

* Statistics Toolbox. The Statistics Toolbox builds on the computational and graphics capabilities of MATLAB to provide: 1) statistical data analysis, modeling, and Monte Carlo simulation 2) building blocks for creating your own special-purpose statistical tools, and 3) GUI tools for exploring fundamental concepts in statistics and probability.

* Symbolic Math Toolbox. The Symbolic Math Toolbox contains functions for symbolic algebra, exact linear algebra, variable precision arithmetic, equation solving, and special mathematical functions. Its underlying computational engine is the kernel of Maple. The Extended Symbolic Math Toolbox augments the functionality to include Maple programming features and specialized libraries.

* System Identification Toolbox. This is a toolbox for parametric modeling. Identified models are in transfer function form (either z transform or Laplace transform) and state-space form (e.g., ARMA models or Box-Jenkins models).

* Chemometrics Toolbox. This toolbox contains a library of functions that allows you to analyze data based on chemometrics methods including multiple linear regression, classical least squares, inverse least squares, Q-matrix, factor based methods, principle component regression, and partial least squares in latent variables. There are also useful functions for plotting data.

* Frequency Domain System Identification Toolbox. This toolbox contains tools for accurate modeling of linear systems with or without delay. The models are transfer functions in s-domain or in z-domain. The procedures include excitation signal design, data preprocessing, parameter estimation, graphical presentation of results, and model validation (tests, uncertainty bounds, modelling errors).

* Hi-Spectm Toolbox. The Hi-Spectm Toolbox, a Partner Series Toolbox, was created by Jerry Mendel, C.L. (Max) Nikias, and Ananthram Swami. The Hi-Spec Toolbox is a collection of MATLAB routines whose primary features are functions for:

* Higher-order spectrum estimation either by conventional or parametric approaches

* Magnitude and phase retrieval

* Adaptive linear prediction

* Harmonic retrieval and quadratic phase coupling

* Time-delay estimation and array signal processing

Toolkits are also available from The Mathworks, Inc. Toolkits are colections of M-files associated with books. These are available from the publisher or from ftp.mathworks.com in /pub/books.

* Control of Spacecraft and Aircraft Toolkit. This is a package of MATLAB programs to demonstrate the concepts discussed in the text "Control of Spacecraft and Aircraft," by Arthur E. Bryson. (1994) Princeton University Press, 1994.

* Signal Processing Examples Toolkit. This is a package of MATLAB programs to demonstrate the concepts discussed in the text "Computer-Based Exercises for Signal Processing Using MATLAB," by C. Sidney Burrus, James H. McClellan, Alan V. Oppenheim, Thomas W. Parks, Ronald W. Schafe, and Hans Schuessler. (1994) Prentice Hall.

* Delta Toolkit. This is a toolkit for analysis using the delta transform, an approach to unifying continuous and discrete systems theory without use of the z transform. It is available free to purchasers of "Digital Control and Estimation: A Unified Approach," by Graham Goodwin and Rick Middleton.

* Numerical Methods for Physics Toolkit. This is a toolkit for which demonstrates the concepts discussed in the text "Numerical Methods for Physics Using MATLAB," by Alejandro Garcia. (1994) Prentice Hall. It is available free to purchasers of this text.

* Numerical Methods for Mathematics, Science and Engineering Toolkit. This is a toolkit for which demonstrates the concepts discussed in the text "Numerical Methods for Mathematics, Science and Engineering, Second Edition," by John H. Matthews. (1994) Prentice Hall. It is available free to purchasers of this text.

* Introduction to Linear Algebra Toolkit. This is a package of MATLAB programs to use with MATLAB in learning and experimenting with linear algebra. The toolbox is coordinated with the text: "Introduction to Linear Algebra," by Gilbert Strang. (1993) Wellesley-Cambridge Press Box 812060 Wellesley MA 02181.

* Templates Toolkit . The M-files were created to supplement "Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods," by Richard Barrett, Michael Berry, Tony Chan, James Demmel, June Donato, Jack Dongarra, Victor Eijkhout, Roldan Pozo, Charles Romine, and Henk van der Vorst (SIAM, 1994).

* Digitale Signalverarbeitung, Grundlagen und Anwendungen, Beispiele und Uebungen Toolkit. This is a toolkit for which demonstrates the concepts discussed in the text "Digitale Signalverarbeitung, Grundlagen und Anwendungen, Beispiele und Uebungen mit MATLAB," by Daniel Ch. von Grunigen. It is available free to purchasers of this text.

1.1.10. How do I contact The MathWorks about MATLAB via email?

Here you go ...

* support@mathworks.com Technical support

* suggest@mathworks.com Product enhancement suggestions

* bugs@mathworks.com Bug reports

* doc@mathworks.com Documentation error reports

* subscribe@mathworks.com Subscribing user registration

* service@mathworks.com Order status, renewals, passcodes

* info@mathworks.com Sales, pricing, general info.

* digest@mathworks.com Submission and questions for the digest

1.2. Product Information

1.2.1. What's new in MATLAB 4.2?

Here's a summary of the major additions and changes:

* Ability to produce hpgl format files

* Ability to import graphs into Adobe Illustrator '88

* Ability to save a figure and load it back into MATLAB

* Better, faster graphics

* DDE capability for the PC

* Online documentation for UNIX systems

* International Character Support (limited)

* Many memory leak fixes

1.2.2. When will MATLAB 4.2 be released on the various platforms?

The PC, SunOS, DEC Alpha, DEC Ultrix, Solaris 2.2 and 2.3, Macintosh, Power Macintosh and HP700 versions have all been released. Other UNIX platforms and the VMS version will follow shortly.

1.2.3. How does MATLAB perform on machine X?

The following are the benchmarks in seconds for some standard operations:
Platform      Loops           LU            Sparse         3-D        2-D

IBM RS         1.38          0.67            1.93          2.60       1.78
6000/590

HP 735         1.35          1.34            2.52          2.43       2.14

SPARC          2.18          1.94            3.41          2.73       2.53
20/62

DEC Alpha      2.88          2.58            2.68          5.67       4.22
3500

SGI Indy       3.55          2.40            4.12          5.20       5.25
R4000

SPARC          3.48          2.89            4.78          5.20       5.23
10/41

PC             4.69          3.96            3.45          7.24       6.28
Pentium/90

Mac Power      4.78          3.99            3.53          7.77       7.91
PC 8100

SPARC 2       10.00         10.00           10.00         10.00      10.00

PC 486         5.59          9.96            8.26         13.70      12.77
DX2/66

PC Laptop     14.10         15.40           13.20         30.50      25.00
486 DX2/40

Mac Quadra    26.30         18.40           26.60         36.50      29.50
700

Mac Power     34.00         84.60           74.80         65.40      65.40
Book 165C

1.2.4. What's new with SIMULINK?

SIMULINK has added the following features in version 1.3:

* Vectorization of blocks

* Scalar expansion of inputs

* Automatic routing of block connections

* Wide vector lines

* Sample time coloration of model

* Enhanced S-functions

* Many new blocks!

1.2.5. What's new in Signal Processing Toolbox version 3.0?

The toolbox now offers enhanced filter design tools for digital and analog filters. Capabilities include the design of optimal least-square filters, minimum order estimation for FIR filters designed with remez, support for cascade filter implementation (second order sections decomposition), and analog Bessel filters. The toolbox has new functions to compute parametric models of signals and linear systems. In addition, there are now graphical demonstrations to provide easy exploration of filter parameters.

1.2.6. What's new in Neural Network Toolbox version 2.0?

Some significant improvements include the addition of trainlm, the Levenberg-Marquardt training algorithm, radial basis functions for the efficient design of supervised feedforward networks, and the recurrent Elman network, which allows you to create networks that can both recognize and generate temporal patterns.

1.2.7. Can a C or FORTRAN subroutine be called directly from MATLAB?

Yes, using "MEX-files." MATLAB's MEX-file facility allows any C or FORTRAN subroutine to be called directly from MATLAB. The MEX-file facility dynamically links your C or FORTRAN subroutine to the MATLAB program at run time.

1.2.8. Can I call MATLAB routines from my C or FORTRAN programs?

Yes, there are two ways. The first is using "MEX-files." MATLAB's MEX-file facility allows any C or FORTRAN subroutine to be called directly from MATLAB. The MEX facility dynamically links your C or FORTRAN subroutine to the MATLAB program at runtime. From inside your C or FORTRAN subroutine, you can then call any MATLAB function. To call a MATLAB function from your program, you start MATLAB, then call your program. Your program is then in control and can access any MATLAB function.

The second way to call MATLAB routines from your program is to use MATLAB as a computational engine. A set of subroutines is provided that allows you to start MATLAB, send data and commands to it, get data back, and terminate MATLAB. This way you can call any MATLAB routine from your FORTRAN or C function.

1.2.9. Student MATLAB 4.0

1.2.9.1. What is new with Student MATLAB 4.0?

The latest is the Student Edition of MATLAB version 4, based on the professional version 4.2. It is published by Prentice-Hall and you should be able to order through your college bookstore (assuming you're a student). You should check with your bookstore on pricing. If your bookstore needs to order it, the ISBN information is:

Macintosh version (disks and user guide): ISBN #0-13-184987-5

MS-Windows version (disks and user guide): ISBN #0-13-184995-6

It includes the Signals and Systems Toolbox, a collection of routines from the professional Signal Processing Toolbox and the Control System Toolbox; if you're familiar with the previous student edition, the toolbox is enhanced from the previous one. It has a number of filter design tools, including Parks-McClellan. In addition, the student edition includes a version of the Symbolic Math Toolbox, based on the Maple V compute kernel.

The Mac Student Edition of MATLAB does not include native PowerMac support because our PowerMac version was not available several months ago when we had to send the Student Edition master off to Prentice-Hall for manufacturing.

We have every intention of providing Macintosh Student Edition users with native PowerMac support. This will happen after we release the professional version of MATLAB for the PowerMac and when we get the new Student Edition master disks into the Prentice-Hall pipeline.

1.2.9.2. Why does Student MATLAB hang my machine after the MATLAB banner is displayed?

This happens from time to time, depending on your machine, because of the way MATLAB tries to compensate for the Math Coprocessor (which is not required). There is only one version of Student Edition for PC's. Here are two fixes for the problem:

OPTION 1:

Edit the matlab.bat file, add the following line above the pcmatlab line, set N087=1, so it will look like this:

set NO87=1 (there are no spaces on either side of the =, and that is a letter O not the number 0.)

pcmatlab .....

OPTION 2:

1. Go to the MATLAB bin directory (cd matlab/bin)

2. Copy PCMATLAB.EXE to PACMATLAB.ORG.

3. Rename PCMATLAB.EXE to PCMATLAB.DAT (using the DOS ren command)

4. At the DOS prompt, type debug pcmatlab.dat and press enter. You will be at the left margin with a minus sign.

5. At the minus, type rcs and it will return CS xyyy where x and y are numbers. You will then be at the colon prompt.

6. At the colon prompt, hit return and you'll get back the minus prompt.

7. At the minus prompt, enter e zyyy:11 where z=x+3, then press return. You should get back zyyy:0011 25.

8. Immediately following zyyy:0011 25. type D followed by a space. This should return 3C. on the same line.

9. Immediately following 3C. type 3F followed by a space. This should return FF. on the same line.

10. Immediately following FF., type 0 (zero) and press return. You will be back at the minus prompt.

11. Enter w and press return. The text Writing 51F92 bytes will be displayed and you will be back at the minus prompt.

12. Enter q and press return. You will be back at the DOS prompt.

13. Rename PCMATLAB.DAT to PCMATLAB.EXE (using the DOS ren command).

1.2.9.3. How do I print using the Student Edition?

Directions on how to print using the Student Edition of MATLAB can be found in the Student Edition manual on pages 27-28.

1.2.10. Is there a MATLAB compiler?

A MATLAB compiler is currently in development. The release date is to be determined.

1.3. User Questions

1.3.1. General MATLAB Questions

1.3.1.1. How do I import graphics into other applications?

The MATLAB (version 4) print command provides a -deps argument which provides an Encapsulated PostScript file of your plot. Some people have reported various problems getting this to work. Some suggestions:

Removing the last line %%EOF from the eps-file.

Use the pstoepsi filter from Doug Crabill (dgc@cs.purdue.edu).

Use bbps and GhostScript. bbps.shar is available via anonymous ftp on csi.jpl.nasa.gov. You'll need to get GhostScript from your nearest GNU ftp site.

Also, there is a technical note written on this topic available on our anonymous ftp server. It can be found in pub/tech-support/tech-notes/mat4.txt.

1.3.1.2. How do I run MATLAB in the background under UNIX? MS Windows?

In UNIX: The nohup command and unsetting the display will allow you to run MATLAB in the background successfully even when you logout.

Try the following:

set OLDDISPLAY=$DISPLAY

unsetenv DISPLAY

nohup matlab < filein > fileout &

setenv DISPLAY $OLDDISPLAY

where filein is the M-file you want to run and fileout is the file you want the output to go to. To set this up as a C shell script, write a file called matbat as:

#!/bin/csh set OLDDISPLAY=$DISPLAY

unsetenv DISPLAY nohup matlab < $1 > $2 &

setenv DISPLAY $OLDDISPLAY

To run this file, issue the command as:

matbat infile outfile

In MS Windows: You need to set the ratio for applications running in the foreground as opposed to running in the background. This ratio will determine how well you can run MATLAB in the background. To set this ratio, go into 386 Enhanced in your Windows Control Panel. You can change your ratio here.

1.3.1.3. Why doesn't MATLAB run as fast as I expect it to?

There are several things that can make MATLAB run slowly. FOR loops take a long time to run in MATLAB (relatively). You should avoid using them if at all possible, or have your for loops run in MEX-files. If you are using scripts rather than functions, then MATLAB loads your script into memory one line at a time, every time you call it. Functions are compiled into pseudo-code and are loaded into memory the first time they are called. Subsequent calls to the function are executed more quickly.

Make sure that you don't have any other large applications running in the background and that there aren't a lot of other people logged onto your machine. These things can also cause MATLAB to run slowly.

1.3.1.4. How can I change the default window size, colors, etc., in MATLAB?

From gray@SCR.slb.com ... If you're running MATLAB 4.x, something like the following should appear in your startup.m file:

set(0,'DefaultFigurePosition',[5,5,505,405])

set(0,'DefaultFigureColor',[0,0,0]) %%N.B this has side

%%effects.

set(0,'DefaultAxesFontName','times')

set(0,'DefaultTextFontName','times')

set(0,'DefaultAxesFontSize',12)

set(0,'DefaultTextFontSize',12)

or from Brian Fitzgerald <fitzgb@mml0.meche.rpi.edu> ...

figure(1)

set(1,'Position', [ 10 10 610 610])

1.3.1.5. How do I manipulate colormaps?

When you use a function that calls a colormap, the function assigns values in the matrix to certain values in the default colormap. The lowest value in your matrix is assigned to the first color in your colormap.

There is a colormap command in MATLAB, which allows you to set your colormap to 10 different sets of colors. For example, colormap cool gives you shades of cyan and magenta while colormap jet gives you shades of blue.

You can set a limit on your colors using the functions caxis, cmin, and cmax. These functions let you define the range of colors you will be using.

1.3.1.6. Is there a topical help function, like 'apropos'?

Yes. The function you're looking for is lookfor (in MATLAB 4).

>> lookfor fourier

FFT Discrete Fourier transform.

FFT2 Two-dimensional Fast Fourier Transform.

IFFT Inverse discrete Fourier transform.

IFFT2 Two-dimensional inverse discrete Fourier transform.

FOURIER Graphics demo of Fourier series expansion.

DFTMTX Discrete Fourier transform matrix.

1.3.1.7. How can I get information about undocumented functions (like comet) in MATLAB?

Most things in the /demos directory are not described in the MATLAB User's Guide. There are lots of goodies there. In 4.0, the demos are the best place to see examples of Handle Graphics.

There are other undocumented functions in directories other than /demos. Some of them are "worker" functions that are unlikely to be used directly; they are simply called by other functions. A few, like comet and comet3, were written after the MATLAB User's Guide was sent to the printer. You should always check the README file for late-breaking news and information.

1.3.1.8. How does the Random generator work?

The algorithm for the rand function can be found in S. K. Park and K. W. Miller, "Random Number Generators: Good ones are hard to find," Comm. ACM, vol. 32, n. 10, Oct. 1988, pg 1192-1201. The formula used for the seed is:

seed=(7^5*seed)mod(2^31-1)

If you want to set the initial seed to an random value, type the following at the MATLAB prompt:

rand('SEED',fix(100*sum(clock)))

This will use the clock to set the seed.

1.3.1.9. Is there a Pseudo-Random Binary Sequence (PRBS) generator in MATLAB?

There is a PRBS generating M-file in the new Frequency Domain System Identification Toolbox, for lengths 2^2-1 to 2^30-1. Its name is mlbs (for Maximum Length Binary Sequence).

1.3.1.10. What is the numeric precision of MATLAB?

In MATLAB, numeric quantities are represented as double precision floating point numbers. On most computers, such numbers have 53 significant binary bits, which is about 15 or 16 decimal digits.

1.3.1.11. How do I run MATLAB in batch mode?

Here is an example of how to run MATLAB in batch mode from your UNIX prompt:

Bourne shell example: (file called atfile.sh)

TERM=; export TERM

matlab > inline.out << EOF

a = [1 2]

quit

EOF

Sample at command on Sun: (-s says use the Bourne shell)

% at -s now + 1 min atfile.sh

C shell example: (file called atfile.csh)

setenv TERM

matlab >! inline.out << EOF

a = [1 2]

quit

EOF

Sample at command on Sun:

% setenv SHELL '/bin/csh -f'

% at now + 1 min atfile.csh

% setenv SHELL /bin/csh

In summary,

Define TERM in the script before you call MATLAB and make it part of the environment. Be sure that the right shell is used to execute the script. If your script is a C shell, you must do the SHELL change in order not to get any extra mail messages from the job. remember that -f means that your .cshrc file will not be executed before you run the script. So, you cannot use any of the parameters set in the script.

1.3.2. Matrices

1.3.2.1. What is the largest matrix MATLAB can handle?

MATLAB itself has no limits on matrix or vector sizes. There are no fixed-size arrays dimensioned within the MATLAB program. MATLAB uses the dynamic memory allocation and virtual memory facilities provided by most operating systems to obtain its memory. Any limits on memory and hence matrix size are those imposed by the operating system or the hardware. On most computers, these limits can be set arbitrarily large by the user or the system manager.

The Student Edition version is limited to variables of size 32 by 32.

1.3.2.2. How does MATLAB index its matrices?

MATLAB began as a FORTRAN program and we have kept the convention of beginning our indices at one instead of at zero. You also cannot have negative indices to vectors of matrices.

1.3.2.3. Can MATLAB handle multidimensional arrays?

Many MATLAB users commonly ask the question, "Can I use multidimensional arrays in MATLAB?" The answer is both yes and no. No, in that multidimensional arrays are not built into MATLAB. MATLAB's internal data stucture is limited to a two-dimensional matrix. But you can create your own functions in the MATLAB language to handle multidimensional arrays. The following is an example that maps a three-dimensional matrix to a single vector. The indices are passed to a function as if it were a three-dimensional matrix. Then the indices are translated to a single vector with corresponding offsets. The exact implementation will be specific to what you want to accomplish.

function position = index3(d,i,j,k)

%INDEX3 POSITION = INDEX3(d,i,j,k) index a 3-D array

% d is a vector that specifies the dimensions on the array

position = (i+(j-1)*d(2)+(k-1)*d(2)*d(3));

The following is an example of how you might use this function.

D = [9 9 9]; % D give the dimensions as 9x9x9

A = 1:(9*9*9); % A is where your 3D data is % stored

A(index(D,5,4,4)) = 77; % Write to it

B = A(index(D,5,4,4)); % Read from it

You can create N-dimensional arrays with different limits on each dimension. The main difference is that you would change how the offset is indexed through your matrix. Each additional dimension would require a corresponding offset. You can add error checking for the indices to make sure you do not go out of bounds.

1.3.2.4. How can I initialize a low rank matrix easily?

Here's "Tony's trick," attributed to Tony Booer of Schlumberger:

To initialize a matrix with values "a" in the first row and values "b" in the second row, do the following:

[a(1,ones(1,m)) ; b(1,ones(1,m))]

1.3.3. Functions

1.3.3.1. Why, when I edit a function file in MATLAB, is the change not seen by MATLAB until everything is cleared or MATLAB is restarted?

When you write an M-file in MATLAB, you can either write a script or a function. The difference is that a script is read from the disk and parsed line by line each time it is called. A function is loaded into RAM for execution. Because it is loaded into RAM, when you edit a function, that change is not loaded into RAM until a call to the new function is made. To get MATLAB to recognize your edited function, type clear functions to clear all functions, or clear <function name> to clear just your function out of RAM.

1.3.3.2. How can I get the parser to accept a dummy reference without an error?

MATLAB parses code to look for syntax errors. When the parser encounters a name with two or less arguments, it lets them pass since they might be a variable with indices. If it encounters a name with three or more arguments, MATLAB knows it cannot be a variable, so the error message is returned. If you don't want the parser to snag the function, specify one with tw0 or fewer arguments.

1.3.3.3. Is there a GNU emacs editing mode for MATLAB?

A GNU emacs 'matlab-mode' is available via anonymous ftp from

csi.jpl.nasa.gov as pub/matlab/util/matlab-mode.el or,

ftp.mathworks.com as /pub/contrib/tools/matlab-mode.el.

1.3.3.4. Does MATLAB have a debugger?

Yes, MATLAB does have a debugger. To find out more, type help debug at the MATLAB prompt.

1.3.4. eval Command

1.3.4.1. How does the eval command work?

The eval command evaluates any expression given as its input. This is described in detail in a technical note which can be found on the ftp server in pub/tech-support/tech-notes/mat3.txt.

1.3.4.2. How can I use a filename that is a variable as an input argument to the load, save, and print functions?

name = 'xyz.mat';

eval(['save ', name]);

eval(['load ', name]);

name = 'myfigure.ps';

eval(['print ',name]);

1.3.5. MATLAB Functions

1.3.5.1. Why was fsolve removed from MATLAB Version 4?

The algorithms used by fsolve were not numerically well behaved. MathWorks did not feel that these algorithms met the standards required for approved software. We recommend the version of fsolve in the Optimization Toolbox . If your site doesn't have the Optimization Toolbox, you can get the old version of fsolve from

ftp.mathworks.com in /pub/contrib/optim/fsolve35.

1.3.5.2. What is griddata? How do I use it to contour irregularly spaced data?

griddata is a function that interpolates your data to generate evenly spaced data for plotting.

Example: x,y,z => irregularly spaced data

xmin=min(x);

ymin=min(y);

xmax=max(x);

ymax=max(y);

xi=xmin:0.02*(xmax-xmin):xmax;

yi=ymin:0.02*(ymax-ymin):ymax;

zi=griddata(x,y,z,xi',yi);

contour(xi,yi,zi)

1.3.5.3. What is the sign convention used in MATLAB's fft routines?

The fft in MATLAB is defined as sum(x(i)*exp(-j*i*k/N)) and not sum(x(i)*exp(j*i*k/N)). The first version is traditionally used by engineers, the second version by mathematicians.

1.3.5.4. How do I fit a curve in MATLAB?

There are many ways to fit a curve in MATLAB. The most common is to use polyfit to fit your data to a polynomial. Here is an example of how to use polyfit to fit data:

x = 1:10;

y = exp(x); % create exponential data to be fitted

c = polyfit(x,y,9); % generate coefficients for a fitted % polynomial of degree 9

yfit = polyval(c,x); % evaluate the polynomial at x

plot(x,y,'yo',x,yfit,'r-') % plot the results

There is a technical note on fitting a function to data using leastsq which can be found on the ftp server under pub/tech-support/tech-notes/math4.txt.

1.3.6. File I/O

1.3.6.1. How do I use fread, fwrite, and fprintf?

fread, fwrite, and fprintf are all similar to their C counterparts and are used to read and write data to a file. Each of these requires the use of a file identifier. These functions allow you to specify the format in which you would like your data read or written.

To find out more, take a look at the online help available for these functions. Also, there is a technical note describing how to load and save data in MATLAB which can be found on the ftp server under pub/tech-support/tech-notes/io1.txt.

1.3.6.2. How can I store the result of ls *.dat in a variable?

[tmp,list] = unix('ls *.dat');

1.3.7. Differential Equations

1.3.7.1. Can MATLAB solve Ordinary Differential Equations (ODE)?

MATLAB has four basic functions to solve ODE's, quad, quad8, ode23, and ode45. quad uses an adaptive recursive Simpson's rule, quad8 uses an adaptive recursive Newton Cotes 8 panel rule, and ode23 uses the Runge-Kutta method. In addition to ode23, there is an ode45 function, which uses a 4th and 5th order Runge-Kutta as opposed to ode23's 2nd and 3rd order.

1.3.7.2. How do I pass in extra parameters to ode and quad?

ode23 and ode45 are called as follows:

= ode45('yprime', T0, Tfinal, Y0)

where the inputs to the function are:

F - String containing name of user-supplied problem description.

Call: yprime = fun(t,y) where F = 'fun'.

t - Time (scalar).

y - Solution column-vector.

yprime - Returned derivative column-vector; yprime(i) = dy(i)/dt.

t0 - Initial value of t.

tfinal- Final value of t.

y0 - Initial value column-vector.

tol - The desired accuracy. (Default: tol = 1.e-6).

trace - If nonzero, each step is printed. (Default: trace = 0).

The call to quad and quad8 is as follows:

Q = quad8(F,A,B,TOL,TRACE)

However, if you want to pass extra parameters to the function, do as follows:

Q = quad8('F',A,B,TOL,TRACE,P1,P2,...)

This allows coefficients P1, P2, ... to be passed directly to function F:

function g=f(a,b)

G = F(X,P1,P2,...).

To use default values for tol or trace, you can pass in the empty matrix.

For more information, take a look at the technical note on this topic. It can be found on the ftp site in pub/tech-support/tech-notes/math1.txt.

1.3.7.3. How do I do double integration in MATLAB?

A technical note has been written on how to do double integration in MATLAB. It can be found on the ftp site in pub/tech-support/tech-notes/math2.txt.

1.3.8. Memory

1.3.8.1. What can I do when MATLAB tells me I'm out of memory?

If the OUT OF MEMORY error message is encountered, there is no more room in memory for new variables. You must free up some space before you can proceed. One way to free up space is to delete some variables (see clear). Another is to issue the command pack (see pack). pack compresses the data in memory, and open up larger contiguous blocks.

Here are some additional system specific tips:

MS-Windows: Increase the swap space by opening the Control Panel, double-clicking on the 386 Enhanced icon, and pressing the Virtual Memory button.

Macintosh: Under Multi-Finder, change the application memory size by using Get Info on the program icon. Under Single-Finder, install more memory.

VAX/VMS: Ask your system manager to increase your working set.

UNIX: Ask your system manager to increase your swap space.

1.3.9. Student Edition

1.3.9.1. Why does my Student Edition hang my machine after the MATLAB banner is displayed?

This happens from time to time, depending on your machine, because of the way MATLAB tries to compensate for the Math Coprocessor (which is not required). There is only one version of Student Edition for PC's. Here are two fixes for the problem:

OPTION 1: Edit the matlab.bat file, add the following line above the pcmatlab line, set N087=1, so it will look like this:

set NO87=1 (there are no spaces on either side of the =, and that is a letter O not the number 0.)

pcmatlab .....

OPTION 2:

Go to the MATLAB bin directory (cd matlab/bin)

Copy PCMATLAB.EXE to PACMATLAB.ORG.

Rename PCMATLAB.EXE to PCMATLAB.DAT (using the DOS ren command)

At the DOS prompt, type debug pcmatlab.dat and press enter. You will be at the left margin with a minus sign.

At the minus, type rcs and it will return CS xyyy where x and y are numbers. You will then be at the colon prompt.

At the colon prompt, hit return and you'll get back the minus prompt.

At the minus prompt, enter e zyyy:11 where z=x+3, then press return. You should get back zyyy:0011 25.

Immediately following zyyy:0011 25. type D followed by a space. This should return 3C. on the same line.

Immediately following 3C. type 3F followed by a space. This should return FF. on the same line.

Immediately following FF., type 0 (zero) and press return. You will be back at the minus prompt.

Enter w and press return. The text Writing 51F92 bytes will be displayed and you will be back at the minus prompt.

Enter q and press return. You will be back at the DOS prompt.

Rename PCMATLAB.DAT to PCMATLAB.EXE (using the DOS ren command).

1.3.9.2. How do I print using the Student Edition?

Directions on how to print using the Student Edition of MATLAB can be found in the Student Edition manual on pages 27-28.

2. Graphics

2.1. Using get and set

2.1.1. What is a handle?

A handle is a number assigned by MATLAB to a graphics object. For example, you can have a handle to each object in a plot that contains many objects such as lines, patches, and surfaces. Once you know the handle to an object, you can alter its properties. To find out what properties are associated with each object, see axis, figure, line, patch, surf, root, and image. If you wanted to get the handle to a line when you plot it, you would do the following:

handle=plot(x,y)

2.1.2. How do I use get and set?

You can either get or set a property of an object in the following manner:

get(handle,'PropertyName')

set(handle,'PropertyName','PropertyValue')

Two common handles are gca and gcf which stand for 'get current axes' and 'get current figure', respectively. If you use gca or gcf as the handle in your get or set statement, you will be able to change the properties of the current figure or current axes without previously defining their handles.

For more information, look at the MATLAB technical note written on this topic. It can be found on the ftp site in pub/tech-support/tech-notes/gr12.txt.

2.1.3. What properties can I control?

To find out about an object's properties, type the following:

set(handle)

This returns a list of all the properties associated with that object as well as each property's optional settings. The settings in { } are the default settings.

2.1.4. How do I change the default settings for an object's properties?

To set the default setting for an object, you first need to know the ancestor of the object whose property you wish to set. To find the parent of an object, type the following:

h=get(object's_handle,'Parent')

To set the default, type the following:

set(h,'DefaultObjectPropertyName','PropertyValue')

Don't put any spaces in the DefaultObjectPropertyName expression. A good example of how to do this is the following:

set(gca,'DefaultLineLineWidth',10)

Any line you plot after this statement will have a line width of 10.

2.1.5. How do I change the default settings back to their original settings?

Set the default settings just as explained above, but use factory for the property value. For example, if you changed the default line width to 10 as above and then you wanted to set it back to the original setting, you would type:

set(gca,'DefaultLineLineWidth','factory')

2.2. Properties of the Figure and the Axes

2.2.1. Fonts

How do I change the font of labels?

When you change the default font name and font size, the factory settings will still be used when drawing the title and lables on the screen. Following is a modified xlabel, ylabel, zlabel, and title to recognize changes to the default FontName and FontSize; however, it would be just as easy to have it recognize changes to all the default text font properties. Below are the revised programs:

<------- XLABEL.M ------->

function xlabel(string)

% XLABEL X-axis labels for 2-D and 3-D plots.

% XLABEL('text') adds text below the X-axis on the current % axis.

%

% See also YLABEL, ZLABEL, TITLE, TEXT.

% Copyright (c) 1984-92 by The MathWorks, Inc.

h = get(gca,'xlabel');

ht = get(text,'fontname');

hs = get(text,'fontsize');

if isempty(h)

h = text('HorizontalAlignment','center');

set(gca,'xlabel',h);

end

set(h,'string',string,'fontname',ht,'fontsize',hs);

<------- YLABEL.M ------->

function ylabel(string)

% YLABEL Y-axis labels for 2-D and 3-D plots.

% YLABEL('text') adds text beside the Y-axis on the current % axis.

%

% See also XLABEL, ZLABEL, TITLE, TEXT.

% Copyright (c) 1984-92 by The MathWorks, Inc.

h = get(gca,'ylabel');

ht = get(text,'fontname');

hs = get(text,'fontsize');

if isempty(h)

h = text;

set(gca,'ylabel',h);

end

set(h,'string',string,'fontname',ht,'fontsize',hs);

<------- ZLABEL.M ------->

function zlabel(string)

% ZLABEL Z-axis labels for 3-D plots.

% ZLABEL('text') adds text above the Z-axis on the current % axis.

%

% See also XLABEL, YLABEL, TITLE, TEXT.

% Copyright (c) 1984-92 by The MathWorks, Inc.

h = get(gca,'zlabel');

ht = get(text,'fontname');

hs = get(text,'fontsize');

if isempty(h)

h = text;

set(gca,'zlabel',h);

end

set(h,'string',string,'fontname',ht,'fontsize',hs);

<------- TITLE.M ------->

function title(string)

% TITLE Titles for 2-D and 3-D plots.

% TITLE('text') adds text at the top of the current axis.

%

% See also XLABEL, YLABEL, ZLABEL, TEXT.

% Copyright (c) 1984-92 by The MathWorks, Inc.

h = get(gca,'title');

ht = get(text,'fontname');

hs = get(text,'fontsize');

if isempty(h)

h = text('horiz','center');

set(gca,'title',h);

end

set(h,'string',string,'fontname',ht,'fontsize',hs);

For more information, see the MATLAB technical note written on this topic. It is located on the ftp site in pub/tech-support/tech-notes/gr2.txt.

2.2.1.1. How do I change the font of text objects?

To change the font name or font size of a text object, do the following

set(h,'FontName','font')

where h is the handle to the text object, and font is the name of the font you wish to use.

For more information, see the MATLAB technical note written on this topic. It is located on the ftp site in pub/tech-support/tech-notes/gr6.txt.

2.2.1.2. How do I change the font of tick labels?

Although undocumented, all the standard text object font properties such as FontName, FontBold, and FontItalic are also properties of axes. For example, typing:

set(gca,'FontStyle','courier')

will change the font of x and y tick labels before they are created. To change the font of existing labels, do the following:

h=get(gca,'Xlabel');

set(h,'FontName',font);

For more information, see the MATLAB technical note written on this topic. It is located on the ftp site in pub/tech-support/tech-notes/gr10.txt.

2.2.1.3. How do I get Greek letters in my text objects?

You can obtain Greek characters from the symbol font. To implement:

h=text(x,y,'string')

set(h,'FontName','courier');

or

set(gca,'FontName','symbol');

text(x,y,setstr(num));

where x and y are the coordinates on the graph where you want to place the Greek symbols, and num is the value from the list of 0-255 characters from the symbol font. To display a table of the symbol font, you can use the following M-file called chart.m.

function chart( fontname )

% CHART Show ANSI-chart like display of characters MATLAB

%can produce.

% CHART( 'fontname' ) will put up a figure

% window with all 255

% characters of the named font in a 16x16 grid.

% Close figure when done, it creates 256 text

% objects. You may want

% that memory back!

% Chuck Packard, The Mathworks, Inc., 25 Jan 93

% This is an unsupported, purely for example, M-

% file.

%

%

% TO USE THIS CHART:

% USE SETSTR( VALUE), WHERE VALUE=( (16*XCOORD)+YCOORD)

%

%

% make a new figure and axis

% (I'm assuming you want to keep the current graph in the

% gcf.)

%

figure;

axis([-1 16 -1 16])

ax = gca;

%

%set font to be used

%

set(ax, 'DefaultTextFontName', fontname )

%

%some other Handle Graphics settings, written out in

%full.

%See manual for more info.

%

set(ax, 'YDir', 'Reverse', 'Box', 'on')

set(ax, 'YTick', 0:15, 'XTick', 0:15)

set(ax, 'DefaultTextHorizontalAlignment', 'Center')

set(ax, 'DefaultTextVerticalAlignment', 'Bottom')

%

%not vectorized like all 'good' MATLAB M-files, but

%easier to understand!

%

x = reshape( 0:255, 16, 16 );

for h=1:16

for v=1:16

text(h-1,v-1,setstr(x(v,h)));

end

end

2.2.1.4. Can I have multiple fonts in one text object?

No, you cannot mix fonts, font styles, or font sizes within a text object.

2.2.2. Lines

2.2.2.1. How do I change the line width?

To change the line width, do the following:

set(h,'LineWidth',size)

where h is the handle to a line and size is the width you want. The default line width is 0.5.

2.2.2.2. How do I change the line style order on printouts?

The following is an M-file that allows you to cycle through the line styles in the order you want when you print:

function prtlines(a1,a2,a3,a4,a5)

% PRTLINES is a front-end to PRINT which converts

% solid lines to various line styles for graphical

% output. The change is transparent to the user.

% Non-solid lines are not affected.

%

% PRTLINES is used in the same manner as PRINT.

%

% The default line styles are:

%

% '. '

% 'o '

% 'x '

% '+ '

% '- '

% '* '

% ': '

% '-.'

% '--'

%

% The line style can be changed by editing the file

% and changing the 'styles' array.

%

% SEE ALSO: PRINT, Properties of LINE

% Written by John L. Galenski III

% All Rights Reserved 10/14/93

% LDM101493jlg

%% PRTLINES is an M-file developed by me for my own

%% personal use, and therefore, it is not supported

%% by The MathWorks, Inc., or myself. Please direct

%% any questions or comments to johng@mathworks.com.

% Create the array of line styles.

styles = [

'. '

'o '

'x '

'+ '

'- '

'* '

': '

'-.'

'--'

];

% Get the Children of the Figure.

a = get(gcf,'children');

% Check the Children of 'a'. If they are

% solid lines, then change their LineStyle

% property.

for j = 1:length(a)

l = sort(get(a(j),'children'));

X = 0;

Add = 0;

for i = 1:length(l)

if strcmp( 'line', get(l(i), 'type' ))

if strcmp(get(l(i),'linestyle'),'-')

X = X + 1;

LINE = [LINE;l(i)];

SI = rem(X,length(styles));

if SI == 0

Add = 1;

end

set(l(i),'linestyle', styles(SI+Add,:));

end

end

end

end

% Construct the PRTCMD.

PRTCMD = 'print';

for x = 1:nargin

PRTCMD = [PRTCMD,' ',eval(['a',int2str(x)])];

end

% Discard the changes so that the Figure is not

% updated.

drawnow discard

eval(PRTCMD)

% RESET THE LINESTYLES

set(LINE,'linestyle','-')

% Discard the changes so that the Figure is not

% updated.

drawnow discard

2.2.2.3. How do I cycle through the line color order?

You can set the default color order for the axes by doing the following:

set(gca,'ColorOrder',A)

where A is an RGB vector of any length.

2.2.3. Positions

2.2.3.1. How do I change the size and position of my figure window?

There is a property of the figure window called Position where the x-position, y-position, width, and height are stored. To change this, do the following:

pos=[x_position, y_position, width, height];

set(gcf,'Position',pos)

2.2.3.2. How do I define an invisible axis?

There is a property of the axis called Visible. You can set Visible to off as follows:

set(gca,'Visible','off')

This is very useful if you want to place text in the figure window with respect to the borders of the figure, rather than with respect to the axes.

2.2.3.3. Which units should I use?

There are five different types of units you can use: inches, centimeters, normalized, points, and pixels. To make sure what you get out of your printer looks like what you have on your screen, we recommend using normalized units.

2.3. Background Color

2.3.1. How do I invert the background on my printout?

set(gcf,'InvertHardCopy','on')

2.3.2. How do I change my background for plots?

To change the background color of your plot from black to white, type cinvert at the MATLAB prompt. To make the default setting white, place the following line in your startup.m file

whitebg

To change the color of your figure window to something other than black or white, type the following:

set(gcf,'Color','red')

2.4. Using MATLAB Graphs with Other Packages

2.4.1. Can graphics be saved as files to be imported back into MATLAB for viewing and alteration?

Yes, in MATLAB version 4.2. A new print command device driver option allows you to save and reload a figure. The command

print -dmfile <filename>

creates two files, filename.m and filename.mat. The M-file contains the necessary object creation and set commands to reproduce the figure. The generated MAT-file also contains the figure data. Handle values are not maintained.

2.4.2. Can I edit MATLAB graphs in other applications?

In MATLAB version 4.2, graphs are produced in such a way that, if your application allows you to view the imported figure, you can edit it.

2.4.3. How do I copy and paste MATLAB graphs to the clipboard?

To copy and paste MATLAB figures to the clipboard, select Edit from the menu at the top of the Figure window. Then select Copy. Your figure now exists in the clipboard. To paste, simply choose Paste from the Edit menu in your application.

2.4.4. Why do my EPS graphics not appear in other applications?

Unless a word processor contains a PostScript interpreter or is running in a Display PostScript windowing system, it can not interpret thePostScript in the EPS file to show you the picture on screen. These word processors normally just show some kind of gray box; often with the name of the file and other information it parses out of some comments

in the EPS file. When you send the Word file to a PostScript printer that gray box with not be drawn, the PostScript image will be rendered.

2.5. Graphical User Interface (GUI)

2.5.1. How do I make a dialog box?

MATLAB version 4.2 has some functions that will help you do this. See help on dialog for more information.

2.5.2. How do CallBacks work? What is the best way to write a CallBack?

A CallBack is the specified action that MATLAB performs when the user selects the menu item to which the CallBack has been assigned. When the button or menu item is selected, the expression contained within the CallBack string is executed. For example:

h=uicontrol('Style','PushButton','String','title',...

'CallBack','disp(''hello'')')'

When you push on the button, hello will be displayed in the MATLAB workspace. The most efficient way to write a CallBack is to make the CallBack a function. That way, the function is stored in RAM and will execute more quickly if you are going to be using the button often.

2.5.3. Where do CallBacks get executed?

CallBacks get executed in MATLAB's main workspace.

2.6. Miscellaneous

2.6.1. Why does waterfall return a blank screen?

There is a bug in the waterfall routine which prevents the edgecolor from being accurately represented. To work around this, issue the following two commands:

h=waterfall(peaks);

set(h,'edgecolor','w')

This will make the edgecolor for the whole waterfall a constant color and allow printing as well as display.

2.6.2. How do you get perspective with 3-D plots?

To change the ratio of the axis in a 3-D plot, you will need to change the xform property of the current axis. The property transforms the 3-D data to be plotted on the 2-D screen. The following M-file will do the trick.

function aspect3(x,y,z)

v = get(gca,'xform');

d = diag([x y z 1]);

set(gca,'xform',v*d);

2.6.3. Why does MATLAB sometimes draw patches out of order?

MATLAB determines the order in which patches are drawn by using the Painter's Algorithm. It determines which patch to draw first by determining which vertices of each patch are closest to you, the viewer. If a few patches have overlapping vertices, then MATLAB must choose which patch to draw first. Sometimes it chooses incorrectly.

2.6.4. How do I use multiple colormaps?

Here is an example:

% Place a gray PCOLOR of PEAKS and hsv SURF of PEAKS in

% the same plot.

clf

hold off

% Set the colormap

colormap([gray(30);hsv(30)])

% Generate the data

= peaks(30);

% Create the Cdata for the PCOLOR and SURFACE plot.

% The Cdata for each plot should be contiguous, and

% not overlap. This will guarantee that they use

% different regions of the colormap.

cd1 = z + abs(min(min(z)));

cd2 = cd1 + max(max(cd1)) + 1;

% Place the PCOLOR

P = pcolor(cd1);

shading interp

% Change the location so that it will be visible when

% the SURFACE is drawn

set(P,'zdata', -30*ones(size(get(P,'zdata'))))

hold on

% Place the SURFACE plot

S = surf(1:30,1:30,z,cd2);

% Change the location so that it does not overlap the

% PCOLOR

%set(S,'zdata',15+get(S,'zdata'))

% Change the Clim used by AXES

set(gca,'clim',[min(min(cd1)), max(max(cd2))])

% Make sure that the VIEW and AXES limits are correct

view(3)

axis([1 30 1 30 -30 30])

% Rules that you need to follow when doing this.

%

% 1) The Cdata values for each plot should

% not overlap.

%

% 2) The range between the minimum and maximum

% values in Cdata should be the same for each

% plot.

%

% 3) The Cdatas must be contiguous.

%

% 4) Set Clim for AXES to range from the

% smallest and largest values of the 2 Cdatas.

2.6.5. What is the difference between pcolor and image?

Each element in the image's CData is used to color a rectilinear patch. The data contains the row of the colormap used to color the patch.

pcolor is a surface plot and its CData is scaled into the colormap. Each element of the CData corresponds to a vertex in the plot. Therefore, the number of rectangles in pcolor is always one row and column smaller than the actual data.

2.6.6. Is it possible to convert a MATLAB movie to MPEG format?

There are two files called "mpegread" and "mpegwrite" on our ftp server in the /pub/contrib/graphics directory. The source code and pre-built MEX-files for some architectures are stored there.

3. Printing

3.1. General

3.1.1. How do I print in MATLAB?

To print a figure window from the command line, type print. If you would like to use any of the options, type print -<option>. For more information, type help print at the MATLAB prompt.

If you are working on a Macintosh or a PC, you can also print from the File pulldown menu on the Figure window (for Macintoshes, make sure the Figure window is the selected window).

3.1.2. How do I print a SIMULINK block diagram?

To print a SIMULINK block diagram, type print -f<systemname> at the MATLAB command line. You can use the options found in help print when printing a SIMULINK diagram.

If you are working on a Macintosh or a PC, you can print from the File pulldown menu, just as you would print a figure.

3.2. GhostScript

3.2.1. What is GhostScript? How do I use it?

GhostScript is a shareware product that converts PostScript to other file formats. You would use this if you wanted to print to a printer that does not accept PostScript. If you just use print without any device, it uses the default printer file format of your system. For a complete listing of GhostScript devices supported by MATLAB, type help print at the MATLAB command line.

3.2.2. Where can I get documentation for GhostScript?

To obtain a copy of use.doc, you can download the file from the MathWorks FTP server in /pub/doc/ghostscript. If you do not have access to FTP, please contact Technical Support.

The makers of GhostScript can be contacted at the following: Phone: 617-876-3296 Email: gnu@prep.ai.mit.edu

3.2.3. Why would I print with a GhostScript device?

Users print with GhostScript devices if they want to generate a file on one system and print on another. Sometimes, you get better quality printouts if you use a device that is specific to your printer, rather than using the default device (which is -dps). Also, if you are printing to a non-PostScript printer, you should specify the type of printer driver you will be using so as not to invoke the default.

3.2.4. What do I do if my printer isn't listed among the GhostScript devices?

If your printer is not listed among the GhostScript devices, look to see if your printer is compatible with one of them. If there isn't a device that is compatible with your printer, just use the print command and MATLAB will choose your system's default printer.

3.2.5. How do you use GhostScript to display PostScript files to the screen from DOS?

There are three ways:

Quickest way:

Create a directory called C:\GS

Copy all files in the directory $MATLAB\GHOSTSCR\BIN, $MATLAB\GHOSTSCR\PS_FILES, and $MATLAB\GHOSTSCR\FONTS to C:\GS (where $MATLAB represents the MATLAB root directory)

Copy the PostScript file to C:\GS

CD to C:\GS

Execute the command GS386 <postscriptfilename>

where <postscriptfilename> is the whole name, including the .ps extension. If for some reason this doesn't work, try

DOS4GW GS386 <postscriptfilename>.

Clean but somewhat cumbersome:

CD to the $MATLAB\GHOSTSCR\BIN directory

Execute the command

GS386 -I..\PS_FILES -I..\FONTS <postscriptfilename>

where here <postscriptfilename> represents the full path name to the postscript file.

Clean and easy but more permanent:

Add $MATLAB\GHOSTSCR\BIN to your DOS path.

In the AUTOEXEC.BAT file, set an environment variable called GS_LIB as

follows:

set GS_LIB = $MATLAB\GHOSTSCR\PS_FILES;$MATLAB\GHOSTSCR\FONTS

(where $MATLAB is replaced by the MATLAB root directory.) Now to use GhostScript you can type gs386 <postscriptfilename> from any directory.

3.3. Printing to a File

3.3.1. How do I print to a file?

To print to a file, type the following at the MATLAB prompt:

print -<device> <filename>

3.3.2. How do I know what option to use?

If you type help print at the MATLAB command line, you will see a list of options. There are two types of options, Windows printing options and miscellaneous options. The miscellaneous options allow you to create an .epsi file (which is an encapsulated PostScript file which can be previewed), append your graph to a file, specify the printer to use, and print a SIMULINK diagram.

3.3.3. How do I print out an HPGL format file?

In MATLAB version 4.2 there is a GhostScript device for HPGL. If you are using MATLAB 4.1.1, 4.1 or 4.0, this option does not exist. The only way to generate an HPGL format file is on the Windows version where you must specify an HPGL printer driver as your default printer. Then, under the File pulldown menu, select Print. In the lower left-hand corner of the Print box is an option to print to a file. Select this option and then select OK. You will then be prompted for an output filename.

3.4. SIMULINK Printing

3.4.1. How do I change fonts in SIMULINK?

SIMULINK models will always print with Times-Roman of point size 10. You cannot change this from inside MATLAB/SIMULINK. You can edit the PostScript file by hand. Be warned, however, the text will not be centered well. You can look near the top of the drawing commands to find the lines:

/Times-Roman findfont

dpi2point mul 0 0 10 dpi2point mul neg 0 0]

The /Times-Roman is the font name you can change. The occurrence of 10 on the second line is the point size.

3.4.2. What do I do if I am getting SIMULINK blocks and no text?

The workaround is to search the PostScript file for a sequence: 0 0 0 0 MR c np and comment out the line using a %. The diagram should then appear in the printout. If it is off center (which it probably will be), there is another place in the .ps file to edit the position on the page. To move the position of a SIMULINK block diagram on the paper, find the instance in the .ps file which has four numbers, then the words: bbox landscape csm. (search on bbox) These numbers represent llx lly ulx ury, where ll is lower left, ur is upper right, etc. Remember, the figure is mapped to landscape, so it gets rotated 90 degrees It may be necessary to play with these numbers to get good figure placement. This bug has been fixed in MATLAB 4.2 / SIMULINK 1.3.

3.4.3. How do I print my SIMULINK diagram on more than one page?

It is not possible to spread your SIMULINK diagram out over more than one page. SIMULINK scales your diagram to fit on one page.

3.4.4. How do I print a SIMULINK model from within an M-file?

This only works for UNIX (because of the print switch, -s). It has been added to the PC for MATLAB 4.2.

function printsys(sys)

open_system(sys);

blocks=get_param(sys,'blocks');

= size(blocks);

for i=1:r

if( get_param([sys,'/',blocks(i,:)],'blocks')~=[] )

open_system([sys,'/',blocks(i,:)])

%disp(blocks(i,:))

print('-s')

end

end

close_system(sys)

3.5. Common Problems

3.5.1. Why does my printer hang when I try to print from the pulldown menu?

This appears to be a problem with the LaserJet IV driver initialization. One way we have found to work around the problem is to print a blank Figure window before printing anything else to the LaserJet. This will print a blank piece of paper, and also has the side effect of properly initializing the driver. After this, you should be able to print without any problems. Note that this blank Figure window only needs to be printed once per Windows session. If you quit and restart Windows for some reason, though, you will need to reprint the blank figure.

This has been fixed in 4.2.

3.5.2. Why, after a long session of MATLAB under MS Windows where many figures printed, do I start to have a problem printing?

When printing several plots, there is a depletion of the system resources under Windows, and even after exiting MATLAB, the resources are not reallocated. This happens to the point where either you can not print anymore or the machine you are working on crashes.

This is more of a problem with Windows than MATLAB. Windows will not reallocate system resources even after you have exited the application. You have to exit Windows and then restart Windows in order to get all of the system resources back.

This can be reproduced both from MATLAB and from MS EXCEL .

There is no clean solution to this problem other than printing to a file first and then sending the file to the printer.

Microsoft anticipates that Windows 4.0 will do a better job in handling system resources.

3.5.3. Why don't my axis labels print correctly?

Sometimes, when you set the paper position in order to generate a small figure, the output title and axis labels are not printed correctly. You may only see the top or bottom half of the text in question depending on where it is in the figure.

So that axis labels and tick mark labels do not overwrite each other, they are always some absolute distance from the axis line. The one caveat is that axis position is relative to the size of the figure and, when rendering to paper, the PaperPosition. When you've got a really small figure or have set the PaperPosition, the axis is very close in absolute coordinates (i.e., it's only 1/2" away rather than 3/4" from the edge of the window or the clipping edge of PaperPosition). The same thing can be seen by making the window really small.

A possible work around:

set(gca,'pos',[.2 .2 .7 .7],'units','norm')

Then adjust your output size to accommodate.

3.5.4. Why can't I print broken lines?

You are probably using the Windows driver or the actual printer driver that came with the printer. Levels 4, 3, 2, and 1 of PCL do not support broken line types. PCL level 5 supports broken line types.

Most other software packages break the lines before presenting them to the printer--we do not. You need to use the GhostScript drivers or use PCL 5, which supports LaserJet 4's and up.

PCL 5---Laser jet 4

PCL 4---Laser jet 4,3

PCL 3---Laser jet 4,3,2

PCL 2---Laser jet 4,3,2,1

In version 4.2 of MATLAB, you have the option of using the Windows/printer drivers to get broken lines but the lines will be thinner. This is a trade off because you get really good fonts from the windows drivers but thin lines and you get less than perfect fonts from the GhostScript drivers but thicker lines. See page 84 of the 4.2 Release Notes.

3.5.5. Why can't I print UI controls?

You can't print UI controls because they are Motif/ Window widgets, and Motif/Windows only draws into an X Window/Window, not hardcopy devices.

UNIX Workaround:

Use the command capture, which captures the current figure into a matrix, and then displays it in another figure window using the image command. The new image can then be printed normally (but the uicontrols in the image don't work, obviously). Since this method involves printing a bitmap image of the screen, the printout may not have as high a print resolution as the hardcopy results of the print command.

PC Workaround:

There is no capture command for the PC version. One workaround is to use Windows handling of PRINTSCREEN. Select the figure that you want to print and press Alt-PrintScreen. A copy of the current window will be placed on the clipboard. This image can be pasted into another application for printing. One undesirable attribute of this workaround is that the Windows window titles and menus are included in the image. These sections of the image can be "cut" using Windows PaintBrush program.

3.5.6. Why, when I use interpolated shading or print surfaces, does my graph look "blocky" when the graph looked fine on the screen?

The reason for this is that when you use shading interp, each pixel can have a different RGB value, but when you try to print this, each surface face is broken into 4x4 blocks and assigned a specific color to each of the blocks. To work around this problem, simply increase the number of faces on your surface and don't use shading interp, use shading flat.

To increase the number of surface faces, use griddata:

[xi,yi,zi] = griddata(x,y,z,0:.1:10,0:.1:100)

where x, y, and z are your original data, 0:.1:10 and 0:.1:100 are your new and increased ranges for x and y.

Then use xi, yi, and zi in your surface command.

For more information, see the MATLAB technical note written on this topic. It is located on the ftp site in pub/tech-support/tech-notes/gr1.txt.

3.5.7. What do I do if my PC beeps and hangs when I try to print?

This problem has been known to occur with the LaserJet 4 and the DeskJet printer drivers. We have found that using the latest versions of these drivers will solve the problem. The latest LaserJet 4 driver is available on the ftp site in pub/tech-support/drivers/laser4_drv. The latest DeskJet driver is also available on the ftp site in pub/tech-support/drivers/desk_drv. In both cases, you should download the entire directory on to your PC and follow the instructions in the README file. If you find that this doesn't solve the problem, please contact Technical Support.


3.5.8. How do I set the default paper type?

The default paper type can be set in the following way. For example, if you wish to set the paper type to 'A4'....

set(0,'DefaultFigurePaperType','A4')

To obtain a list of the available paper types...

set(0,'DefaultFigurePaperType')

The paper type must be set at the beginning of every MATLAB session unless you place it into the startup.m file.

4. License Manager

4.1. Installing MATLAB

4.1.1. Are there step by step instructions for installation?

Yes, these instructions can be found in the README.install file. In addition, a complete guide to the license manager can be found in README.license file which is located in your $MATLAB/etc directory. However, it is important for you to read your Installation Guide first.

4.1.2. When should I run lmdebug?

You should run the script lmdebug if you are unable to start MATLAB. Once you have run the lmdebug script, take a look at what is in the Output of lmstat -a section. This should describe the problem that is keeping you from running MATLAB.

4.1.3. When do I have to run the license manager?

You need to run the license manager in all but the following two cases:

You have demo passcodes (DEMO is located at the end of your encryption codes in your license.dat file)

You have a CPU locked Multi-User License (your hostid is located at the end of your encryption codes in your license.dat file and you have more than key). See page 9 of your Installation Guide if you are running on a VAX or page 1-14 if you are running on a UNIX system.

4.2. License Configurations

4.2.1. How do I set up the license manager so that it runs on a heterogeneous network?

A heterogeneous network means you're running a floating license on, say, both a SUN and a DEC using one license server. You can combine both installations of SUN and DEC MATLAB onto one machine, but we recommend against this since it involves a custom installation. This description assumes that you have a separate DEC area where you will install DEC MATLAB and a separate SUN area where you will install SUN MATLAB.

Install MATLAB from the tape onto each machine, using the install option for STANDALONE/SERVER machines.

For any client machines of the DEC and SUN, make sure the MATLAB client DEC machines have their matlab command access $MATLAB/bin/matlab on the DEC platform. Likewise, SUN MATLAB client machines should have their matlab command access $MATLAB/bin/matlab on the SUN platform.

Decide which machine is the license server. In this example we will consider the DEC machine to be the license server.

The DEC license file should contain the DEC lmhostid, the DEC lm_matlab vendor daemon and passcodes based on the DEC lmhostid.

In the SUN $MATLAB/etc directory, create a link for the license.dat file to point to the DEC $MATLAB/etc/license.dat.

Start the license manager from the DEC license server machine.

Keep in mind that for different platforms to work together, they must be using compatible versions of the license manager. For example, if you have V3.5j on the SUN, you cannot combine it with V4.1 for the DEC since they contain incompatible versions of the license manager. More specifically, the SUN MATLAB will call lmgrd on the DEC and place it in an incompatible state. It will not be able to run properly.

4.2.2. On a UNIX network, how do I run a back-up server configuration?

This configuration is only allowable for floating network licenses. Consider the following license file using a Sun-4 based license manager:

----------------------------------------------------------------------------

#License file for use with FLEXlm version 2.4c.

SERVER pooh 55419ab7 1705

SERVER piglet 554251b8 1705

SERVER rabbit 52006ac1 1705

DAEMON MLM /usr/local/matlab/etc/lm_matlab

FEATURE MATLAB MLM 1 01-jun-2012 99 6B283ACADCE90BE190B7 ""

FEATURE SIMULINK MLM 1 01-jun-2012 99 EB689A7AE885CDB2E0A3 ""

---------------------------------------------------------------------------

To bring up the three license managers interactively, do the following after installation.

Login to pooh. Become root. cd /usr/local/matlab/etc. Run lmstart.

Login to piglet. Become root. cd /usr/local/matlab/etc. Run lmstart.

Login to rabbit. Become root. cd /usr/local/matlab/etc. Run lmstart.

To have the license manager daemons started at boot time, follow the directions in the Installation Guide to place the Bourne shell code fragment into the appropriate boot script.

The /etc/lmboot link must exist on each of the servers. To create this link on a given server, first login to the server and then, as root, run:

# $MATLAB/etc/lmboot -s

where $MATLAB is the location of the MATLAB root directory.

Please note that at least two of the machines must always be running in order to create a network quorum. If only one of the three machines is running, no licenses will be available until a second server regains a running status.

The order of the servers is also important. The first server will be the primary server and if this machine fails, the primary server will be designated as the next server listed in the license file.

You must submit all three servers' hostids in order for the passcodes to be be properly generated for this configuration.

4.2.3. How do I combine license.dat files if I am running another vendor's product that uses FlexLM?

In V2.21 (or older) of the license manager, this was not possible; you could not combine two counted licenses of the same FEATURE names in the license.dat file.

V2.4c of the license manager offered the option to enable multiple FEATURE lines of the same name into one license.dat file.

For this to work, it is necessary to place all the floating license FEATURE lines before all the node-locked FEATURE lines.

To start other vendors' daemons you must create:

A merged license.dat file with all the DAEMON and FEATURE lines associated with each vendor daemon.

A modified $MATLAB/etc/lmboot script. After installation the lmboot script needs to be modifed to know about each additional vendor daemon in the license file. This is so that the temporary license file in /usr/tmp can be created correctly.

This example demonstrates what needs to be done. Consider having both MATLAB and another vendor's daemons started by MATLAB's license manager daemon with the following license file:

----------------------------------------------------------------------------

#License file for use with FLEXlm version 2.4c.

SERVER radical 52201985 1700

#

DAEMON MLM /usr/local/matlab/etc/lm_matlab

FEATURE MATLAB MLM 1 01-aug-1995 3 6B486F9FDB9F99083820 ""

FEATURE SIMULINK MLM 1 01-aug-1995 3 8B38FF3F695F028F93A8 ""

FEATURE Control_Toolbox MLM 1 01-aug-1995 3 2B18BFEF0BB457E414B5 ""

#

DAEMON XXX /usr/local/XXX/license/bin/XXX

FEATURE XXX XXX 3.100 01-aug-1995 1CBB4ACD78C0C77ABE123 ""

---------------------------------------------------------------------------

You need to remember the DAEMON names when making the code changes. In this case the only additional DAEMON name is XXX.

Below is a Bourne shell code section from lmboot. The part between the

"======" lines must be modifed. For each DAEMON you must add three lines such as:

NAME)

ln -s $daemonPath /usr/tmp/$marker.vd$ndaemon

;;

The only thing that should change is NAME. It must be the name of the DAEMON. For PVI it would be

PVI)

ln -s $daemonPath /usr/tmp/$marker.vd$ndaemon

;;

Note that these lines for PVI are already shipped in the script, except the lines are commented out. To activate them simply remove the # or comment character from the beginning of the lines as indicated below. If there are additional daemons, then three more lines for each daemon must be added.

In order for the process command names given by the ps command to look the same across platforms, the symbolic link created in the three-line script section above should refer to a binary daemon program, not a script. This means the daemon path given by the third field of the DAEMON line (referred to as $daemonPath in the script) should be a path to a binary program. Note that for MATLAB this is not true. So a special value for the daemon path which refers directly to the binary is used.

#

#Create temporary license.dat file by copying and modifying the original file

#

rm -f /usr/tmp/$marker.dat > /dev/null 2>&1

rm -f /usr/tmp/$marker.vd* > /dev/null 2>&1

ndaemon=0;

(while read line

do

field1=`echo $line | awk '{print $1}'`

if [ "$field1" = "DAEMON" ]; then

daemonName=`echo $line | awk '{print $2}'` # field 2

daemonPath=`echo $line | awk '{print $3}'` # field 3

ndaemon=`expr $ndaemon + 1`

case "$daemonName" in

# Always assume $MATLAB/etc/$Arch/lm_matlab

# Must use the binary - NO SCRIPTS

ln -s $MATLAB/etc/$Arch/lm_matlab /usr/tmp/$marker.vd$ndaemon

;;

#============================================================

# ADD OTHER DAEMONS HERE. Example, PV-WAVE. Uncomment lines.

# Add other case statments for additional daemons.

#

PVI) # Use the daemonPath - arch binary already

ln -s $daemonPath /usr/tmp/$marker.vd$ndaemon

;;

#============================================================

*) # daemons you forgot

ndaemon=`expr $ndaemon - 1`

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

echo ''

echo 'Sorry! Skipped following DAEMON line. Fix $MATLAB/etc/lmboot script.'

echo ''

echo "$line"

echo ''

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

continue

;;

esac

echo "$line" | sed "s%$daemonPath%/usr/tmp/$marker.vd$ndaemon%"

>> /usr/tmp/$marker.dat

else

echo "$line" >> /usr/tmp/$marker.dat

fi

done) < $licensefile

4.2.4. How do I run two versions of MATLAB on a VAX?

The MATLAB environment, which needs to be modified to run different versions of MATLAB, consists of two logical names.

MATLAB

TOOLBOX

When installed as described by the installation document, the logical names are defined on a system-wide basis at boot time through the execution of MATLAB:[ETC]MATLAB_SYSTARTUP.COM from SYS$MANAGER:SYSTARTUP_V5.COM. (See installation guide steps 8)

Symbols used to invoke MATLAB and its utilities, such as CMEX, are defined on a per-process basis through the execution of MATLAB:[ETC]MATLAB_SYLOGIN.COM from SYS$MANAGER:SYLOGIN.COM at login time. (See Installation Guide step 9)

If you want to maintain a MATLAB v3.5 environment and have the ability to run MATLAB v4.x, omit steps 8 and 9 of the installation procedure. Instead, following completion of the installation procedure, perform the following steps using the editor of your choice:

Copy the lines from MATLAB_SYSTARTUP.COM which define the logical names MATLAB and TOOLBOX to MATLAB_SYLOGIN.COM. The lines in MATLAB_SYSTARTUP.COM look like this:

$ DEFINE/SYSTEM/EXEC/TRANS=CONCEALED MATLAB DISK$USER:[MATLAB.]

$ DEFINE/SYSTEM/EXEC/TRANS=CONCEALED TOOLBOX DISK$USER:[MATLAB.TOOLBOX.]

Place these lines so they are the first commands to executed by the file.

From these lines remove the "/SYSTEM" qualifier, so they look like this:

$ DEFINE/EXEC/TRANS=CONCEALED MATLAB DISK$USER:[MATLAB.]

$ DEFINE/EXEC/TRANS=CONCEALED TOOLBOX DISK$USER:[MATLAB.TOOLBOX.]

Save MATLAB_SYLOGIN.COM and exit. (Do not save MATLAB_SYSTARTUP.COM.)

Now to setup the environment to run V4.x simply type: @DISK$USER:[MATLAB.ETC]MATLAB_SYLOGIN

4.3. Common Error Messages:

4.3.1. Cannot Connect to License Server

Possible Solutions:

Check whether the license daemons are running. Do a ps as indicated in the troubleshooting section of the Installation Guide.

If the license daemons are not running, you should execute lstmart. With a CPU-locked Multi-User license, however, the license daemons do not need to be run, so you should try starting MATLAB and let us know if you're getting any errors.

Check that the DAEMON line in the license.dat file is pointing to the correct location for lm_matlab.

Make sure the host name on the SERVER line in the license.dat file is correct.

Make sure the the UNIX ping <hostname> command returns <hostname> is alive where hostname is the name of the MATLAB server machine. If the ping command returns the error, <hostname> is not responding, then there is a problem with your network configuration such that connection to that machine will fail. Connection to the license daemons will, therefore, also fail.

Make sure that the network software TCPIP is running on your machine. Even for stand-alone machines, the license manager requires TCPIP.

4.3.2. XXX Feature is not Currently Licensed

Possible Solution:

It may be a typographical error in the feature line indicated by the error. For example, this error will occur if Signal_Toolbox is entered as signal_toolbox. Check the error message for typographical errors and case sensitivity in the name of the feature. Make sure the FEATURE line matches the passcodes as generated by The MathWorks, Inc.

4.3.3. Environment Variable of lm_license_file Not Defined

Possible Solution:

The user is running the matlab executable in, say, $MATLAB/bin/sun4, rather than the matlab script in $MATLAB/bin. Note that sun4 can be replaced with any architecture we support, like RS/6000.

You may have the wrong matlab on the UNIX path or you may need to rerun install_matlab to set up the correct paths.

4.3.4. No TCP License Server Exists

Possible Solutions:

You do not have TCPIP software on your machine. To check, execute the UNIX ping command. e.g., ping <hostname> where hostname is the name of the machine from which you're trying to run MATLAB. If ping is successful, see (2) below.

You probably do not have 1700 at the end of the SERVER line in the license.dat file.

4.3.5. Invalid Returned Data From License Server

Possible Solution:

You probably installed the latest version of MATLAB (which uses FLEX 2.4c) without shutting the old (v2.21) license daemons.

This error indicates that you are running a version of FLEXlm older than 2.4c. You need to execute lmstart in V4.1 of MATLAB which executes the lmgrd and lm_matlab license daemons which ship with MATLAB 4.1.

4.3.6. License Server Does Not Support This Feature

Possible Solutions:

You probably received new codes and did not restart the license manager. You can also try doing an lmreread.

Make sure you do not have a typographical error in the FEATURE line spelling.

4.3.7. Unable to Read License File

Possible Solution:

The problem occurs with the logical LM_LICENSE_FILE set to NODE:FILE_SPEC.

MATLAB compiled with the VAX C compiler does not support accessing a license file through DECNET. This is because access to the license file is checked with a C standard runtime library routine called access. The VAX C runtime library access routine explicitly does not support access to a file through DECNET.

LM_LICENSE_FILE must point to a local license.dat file. This license.dat can be a VAX CLUSTER file, which is the equivalent of NFS mounting under UNIX.

5. SIMULINK/MEX-Files/Engine

5.1. SIMULINK

5.1.1. Printing SIMULINK models

5.1.1.1. How do I print my SIMULINK model?

To print a SIMULINK block diagram, type print -f<systemname> at the MATLAB command line. You can use the options found in help print when printing a SIMULINK diagram.

If you are working on a Macintosh or a PC, you can print from the File menu, just as you would print a figure.

5.1.1.2. Why doesn't the text on my SIMULINK diagram print out?

This was a bug in SIMULINK version 1.2 and MATLAB versions 4.0 thru 4.1.1. It has been fixed in SIMULINK version 1.3 and MATLAB version 4.2.

5.1.2. MATLAB Function block

5.1.2.1. Why can't I call any MATLAB function from the MATLAB Function block?

The MATLAB Function block can take any number of inputs, but it must return a vector as an output.

5.1.2.2. What is the difference between the MATLAB Function block and the function block?

The MATLAB Function block can perform any function in MATLAB, whether it is a function you have written or one that comes with MATLAB.

The Function block can use only a limited number of functions (the list of these functions can be found by clicking on Help in the function block). This block uses C routines to perform the calculations and is therefore very fast.

5.1.3. General Questions

5.1.3.1. How do I mask SIMULINK blocks?

There is a technical note on masking SIMULINK blocks, which can be found in pub/tech-support/tech-notes/sim3.txt.

5.1.3.2. Why doesn't linmod return the correct results?

There is a technical note which explains the uses and limitations of linmod which can be found in pub/tech-support/tech-notes/sim2.txt.

5.1.3.3. Can SIMULINK handle complex signals?

No. The current releases through 1.3 are not designed to handle complex data. The real and imaginary parts must be separated and handled independently.

5.1.3.4. How do I use the set_param and get_param functions?

There is a technical note which explains how to use these two functions which can be found on the ftp server in pub/tech-support/tech-notes/sim6.txt.

5.1.4. S-functions

5.1.4.1. What is the flag ordering for S-functions?

SIMULINK makes calls with flags in the following order: 4, 3, 2, 1. It might not call all of these flags, but flag calls are always made in this order, whether or not some flags have been skipped.

5.1.4.2. How do I display values numerically, rather than graphically (with the scope)?

The following is an S-function example, which was written by one of the Technical Support Engineers:

function[sys,x0]=show(t,x,u,flag)

if abs(flag)==0,

hs1=figure('units','normal','pos',[.8 .8 .1 .2]);

hs2=uicontrol(hs1,'style',...

'edit','units','normal','pos',[0 0 1 1],

...'min',0,'max',100);

set(hs2,'string','DIG_SCOPE');

sys=[0 1 0 1 0 0];

x0= hs2;

elseif abs(flag)==2,

tempstr=get( x(1) , 'string' );

newstr=str2mat( num2str(u),tempstr );

% Keep the last 50 values

[m n]=size(newstr);

if m>50,

newstr=newstr(1:50,:);

end

set( x(1) , 'string', newstr);

sys= x(1);

else

sys=[];

end

5.1.4.3. Are there any examples of S-functions in C? FORTRAN?

Aside from the examples, which can be found in the directory /simulink/blocks, our engineers are starting to build a library of examples. To find out more about these, contact support@mathworks.com.

5.2. MEX-Files and Engine

5.2.1. Compilers we support

Some compilers, that are supported by MATLAB, are not compatible with Simulink. Simulink requires specialized 32 bit parameter passing mechanisms. Thus, C compilers such as Borland and Microsoft will not work with Simulink because those compilers create 16 bit DLL's. Watcom and Metaware compilers will create 32 bit DLL's, and are supported by Simulink.

There is a technical note, which contains a list of compilers along with many addresses and phone numbers for compiler companies. This technical note can be found in pub/tech-support/tech-notes/mxeng1.txt.



5.2.2. MEX-File function examples

5.2.2.1. Where can I get C MEX-file function examples?

Aside from the many C MEX-file examples, which can be found in the $MATLAB/exter/src directory, other examples can be found in pub/tech-support/tech-notes/mxeng3.txt. and pub/tech-support/tech-notes/mxeng4.txt.

5.2.2.2. Are there any FORTRAN MEX-file examples?

There are many FORTRAN MEX-file examples which can be found in the $MATLAB/exter/src directory.

5.2.2.3. How do I write a C++ MEX-file function?

A descripton of how to create C++ MEX-file functions is in a technical note which can be found on the ftp server in pub/tech-support/tech-notes/mxeng5.txt.

5.2.2.4. Are there any engine examples?

The following is an example of a program that uses the MATLAB Engine to find the Hankel matrix:

#include <stdio.h>

#include "engine.h"

main()

{

Engine * ep;

char * buffer;

double userdata[3];

int i;

for (i=0;i<3;i++)

{

printf("Enter element #%d: ",i+1);

scanf("%lf",&userdata[i]);

}

ep=engOpen("setenv DISPLAY puff:0; matlab");

if (ep==NULL)

{

fprintf(stderr,"Error opening MATLAB");

exit(-1);

}

if engPutFull(ep,"mystuff",1,3,userdata,NULL)

fprintf(stderr,"Error entering data into MATLAB");

buffer=mxCalloc(201,sizeof(char));

engOutputBuffer(ep,buffer,200);

if(engEvalString("hankel(mystuff)"))

fprintf(stderr,"Error using hankel");

else

printf("Hankel Matrix was \n%s\n",buffer);

mxFree(buffer);

engClose(ep);

}

5.2.3. Common Problems

5.2.3.1. Why an I getting a segmentation violation error?

Segmentation violation errors occur when MATLAB tries to write to an area of memory that is not allowed. Some possible causes of this are improper dereferencing of pointers, use of pointers which contain incorrect values, and writing past the end of a dimensioned array. You should check your MEX-file function to see if any of these possibilities are occurring.

6. Signal Processing

6.1. Filters and Filtering

6.1.1. How do I design a filter with butter/cheby1/cheby2/ellip?

These filters are specified in general by cutoff frequencies and pass- and stopband ripples. Designing them takes two steps. The first step is to call the appropriate function buttord, cheb1ord, cheb2ord, or ellipord to determine the minimum order filter necessary to meet the desired specifications. The second step is to then pass this order (as well as cutoff frequencies and band ripples, for some of these functions) to the design function (butter, cheby1, cheby2, or ellip). Here is an example:

% Design an elliptical lowpass filter with passband cutoff % frequency at 20% of the sampling frequency, and stopband % cutoff frequency at 40% of the sampling frequency. % Passband ripple to be no more than 3dB, and stopband % attenuation greater than 30dB:

% First, generate the specs. Note that the cutoff % frequencies are specified in terms of the Nyquist % Frequency, which is half the sampling

% frequency:

Rp=3; % passband ripple

Rs=30; % stopband attenuation

Wp=.2*2; % Passband cutoff. Multiply by two to convert to % fraction of Nyquist frequency

Ws=.4*2; % Stopband cutoff

% Next, determine minimum order:

[N,Wn]=ellipord(Wp, Ws, Rp, Rs);

% Finally, feed the output of ellipord to ellip to generate % the filter:

[b,a]=ellip(N, Rp, Rs, Wn);

6.1.2. How do I design a filter with remez?

A Remez (or Parks-McClellan equiripple) filter is specified by the order of the filter and the location of its pass- and stopbands. As in the question above, the bands are specified in terms of the Nyquist frequency, not the sampling frequency. The bands specified must be linear, and are not restricted to having a zero slope. To specify the bands two variables, frequency and magnitude, are given. Frequency represents a vector of frequencies specifying the start and end points for each band. Magnitude specifies the corresponding magnitude at the edges of the bands. For example, a bandpass filter, which would have three bands (two stop and one pass), would look like this:

frequency=[0 w_stop1rightedge w_passleftedge... w_passrightedge w_stop2leftedge 1];

magnitude=[0 0 1 1 0 0];

Note that frequency always starts with 0 (DC) and ends with 1 (Nyquist frequency). The command

plot(frequency,magnitude)

will give a rough plot of the desired frequency response.

The following example designs a 10th order Remez filter with a passband from DC to 20% of the sampling frequency, and a stopband from 30% to 50% of the stopband:

N=10; % order

F=[0 0.2 0.3 0.5]*2; % Multiply by two to convert to % fraction of Nyquist frequency

M=[1 1 0 0];

b=remez(10,F,M);

6.1.3. How do I use remez to make a differentiator?

The remez function can also design a differentiating filter. In this case, the filter has one band, and the band's magnitude is zero at DC, and climbs linearly to pi*Fs at the Nyquist frequency. By specifying the string 'differentiator' as an optional fourth argument, remez will give the filter odd phase and relatively weight the filter as a function of frequency, so the filter is more accurate where its magnitude is small and less accurate where its magnitude is large. This example designs an 11th order differentiator for a signal whose sampling frequency is 10000Hz:

Fs=10000;

b=remez(11,[0 1],[0 10000*pi],'differentiator');

6.1.4. Why does butter sometimes design unstable filters?

Filters whose poles are either close together or close to the unit circle are highly sensitive to roundoff and quantization error. Both high order Butterworth filters and Butterworth filters with very low or very high cutoff frequencies have poles close to each other and the unit circle. Therefore, attempts to design these types of Butterworth filters will often generate filters with strange-looking, almost random transfer functions. Unfortunately, since roundoff error is a hardware-limited effect, the only solution for this problem is to use a different type of filter designer, such as ellip or cheby2.

6.1.5. How can I generate a plot of the the transfer function of my filter?

Two functions provided in the Signal Processing Toolbox allow this to be done quite easily. These functions are freqz (for digital filters) and freqs (for analog filters). Calling these functions without any output arguments will automatically generate a magnitude and phase plot in the current figure window. For example, assume that b and a contain the numerator and denominator coefficients for a given filter. To plot the filter's transfer function, type

freqz(b,a)

For an FIR filter (where a equal 1), you can just specify b:

freqz(b)

6.1.6. How do I filter data once I've designed a filter?

Digitally filtering data is done via the functions filter and filtfilt. Filter takes the filter's coefficients as well as the data to be filtered as inputs, and returns the filtered data as an output. For example:

t=0:.001:1;

y=sin(2*pi*t*10)+sin(2*pi*t*200);

[b,a]=remez(20,[0 50 100 500]/500,[1 1 0 0]); % lowpass filter design

yfiltered=filter(b,a,y);

plot(1:length(y),y,1:length(yfiltered),yfiltered)

Filtfilt takes the same inputs and outputs as filter, but performs the filtering operation in both the forward and reverse directions (that is, it is a noncausal filter). This effectively squares the magnitude of the filter, but cancels any phase offset introduced by the filter.

Analog filtering is not supported by the Signal Processing Toolbox. Instead, either SIMULINK or the lsim function from the Control System Toolbox must be used.

6.2. FFT and Spectrum

6.2.1. Why doesn't plot(ifft(fft(x))) plot x correctly?

The Inverse Discrete Fourier Transform is performed by the ifft function. Basically, this function reverses the process of the Fourier Transform, converting a vector containing frequency data into a vector containing time data. In general, ifft(fft(X)) should equal X. However, be aware that due to roundoff error, the result of ifft(fft(X)) may not be exactly the same as X. Specifically, if X is a real vector, ifft(fft(X)) may have a complex component that is very, very small (on the order of machine epsilon). This complex component will still affect the plot function, causing it to plot the imaginary part of ifft(fft(X)) versus its real part, rather than plotting its real part versus its index. Therefore, if you are trying to compare X with ifft(fft(X)) graphically, you should remember to take the real part of ifft(fft(X)). For example:

y=sin(2*pi*(0:0.001:1));

subplot(311)

plot(y)

subplot(312)

plot(ifft(fft(y))) % Note the Y-axis limits!

subplot(313)

plot(real(ifft(fft(y))))

6.2.2. Why doesn't the phase of my pure cosine/sine function look correct?

If you execute the following code, you should see two spikes corresponding to the phase of the pure sine wave:

t=0:.001:1;

y=sin(2*pi*t*200);

plot(angle(fft(y)));

Instead, you get a strange-looking curve. The explaination of this phenomenon is as follows: The signal y is the product of an infinitely long, pure sine wave with a rectangular (boxcar) window. The Fourier transform of the pure sine wave consists of 2 impulses (i.e. delta functions) at 200 Hz and -200 Hz. The Fourier transform of the boxcar window is a sinc functions. When you multiply these two in time, you are convolving them in frequency, so the result in the frequency domain is the sum of two shifted sinc functions, one at 200 Hz and the other at -200 Hz. Thus, there is some small spectral component of the signal even at frequencies other than the fundamental frequency (200 Hz), and it is this spectral content that causes the phase of the signal to look like it does.

6.2.3. How do I scale the results of my fft to obtain a magnitude vs. frequency plot?

This is described in a technical note located on our ftp server in pub/tech-support/tech-notes/sig2.txt.

6.2.4. What is Welch's method?

Many of the spectral estimation functions such as Spectrum, PSD, CSD, TFE, and Cohere use a method of spectral estimation known as Welch's Method. Basically, the following steps are used to transform a time-based vector into a frequency-based vector:

1. The data is broken up into M sections, where M is user-specified.

2. The M sections are detrended, removing linear trends (including the DC

component).

3. The sections are windowed using a Hanning window.

4. The FFTs of the detrended, windowed sections are taken.

5. The magnitude of the FFTs are averaged together and normalized by the square of the norm of the Hanning window, to generate an asymptotically unbiased estimate.

An asymptotically unbiased estimate will have an expected value which approaches the true expected value of the underlying random signal as the number of samples used increases. The averaging in this process causes the variance of the PSD to be diminished by a factor of M. This lowers the floor of random noise in a signal, making it easier to pick out deterministic signals.

6.2.5. How can I make spectrum plot without confidence intervals?

If you are using the spectrum/specplot functions in the Signal Processing Toolbox, and you do not want the confidence intervals plotted along with your PSD, you have two options:

1. Use the psd and csd functions, instead. Calling either of these functions without an output argument will cause them to generate a power plot without confidence intervals.

2. Modify the output of spectrum to set the confidence ranges to NaN. The following are two examples, one for the case of one input to spectrum, and the other for the case of two inputs to spectrum:

One input case

x=rand(1024,1);

P=spectrum(x,128);

P(:,2)=nan*P(:,2);

specplot(P)

Two input case

x=rand(1024,1);

y=randn(1024,1);

P=spectrum(x,y,128);

P(:,6:7)=nan*P(:,6:7);

specplot(P)

6.3. Miscellaneous

6.3.1. When running invfreqs, what does it mean when I get the following message:

Warning: Matrix is close to singular or badly scaled.

Results may be inaccurate. RCOND = xxxxx

This error most often happens in two cases. The first is that part of the transfer function's magnitude is relatively flat (has slope close to zero). The second is that extremely high frequencies (greater than 100MHz) are being specified in the frequency vector.

Many times this warning can be ignored. It is best to inspect the designed filter to see how well it performs. The call to invfreqs in the following example will cause this warning message, but the example shows that the filter still fits the desired curve quite well:

clf;

w=linspace(0,100,1024);

H=1-0.1*(1-1./(1+(j*w).^0.3));

% generate desired frequency response

[b,a]=invfreqs(H,w,5,5);

% design filter with that response

[H1,w1]=freqs(b,a);

% generate freq. resp. of designed filter

plot(w1,abs(H1))

% plot freq. resp. of designed filter

set(gca,'xlim',[min(w) max(w)])

% adjust x-axis limits

hold on

% freeze plot

plot(w,abs(H),'r')

% plot freq. resp. of desired filter in red

hold off

% unfreeze plot

In those cases where one can't ignore the warning message, the following hints may help:

1. For transfer functions with regions of flat slope, sample the flat portion of the transfer function less finely than the non-flat portions. In the above example, you might try

w=[linspace(0,10,1020),linspace(11,100,4)];

This will sample the steeper portion of the transfer function from 0 to 10 Hz 1020 times, and only sample the flatter portion from 10 to 100 Hz only four times.

2. For extremely high frequencies, try scaling the problem down. Design a similarly-shaped filter in a lower frequency band, and then scale the final result up to the desired frequency using the lp2lp function.

6.3.2. Why does decimate introduce a DC offset into my data?

The data to be decimated is first run through an anti-aliasing filter. The default anti-aliasing filter is a 8th order lowpass Chebyshev filter, with the default filter being:

>>[b,a]=cheby1(8,.05,.08);

The transfer function of this filter at DC (H(0)) is:

>>h=freqz(b,a,[0 0]);h=h(1)

h =

0.9943

Since the filtering is done with filtfilt, the transfer function is effectively squared, giving a true DC transfer function of

>>h*h

ans =

0.9886

So the DC component of the signal will be multiplied by 0.9886. One way to avoid this problem is to use decimate with an FIR filter, as demonstrated below:

xd=decimate(x,10,'FIR');

A useful property of the FIR filter in this case is that its DC gain is always 1, so it will not affect the DC offset of your data.

6.3.3. Why does deconv sometimes produce unstable results?

To understand how deconv works, it is best to start with how conv works. If one starts with two inputs A and B, and convolves them together to get C, then in the z-transform domain, this is equivalent to:

C(z) = A(z) * B(z)

where * denotes multiplication. To invert this process, i.e. to deconvolve A from C, would be equivalent to dividing both sides of the equation by A(z). Thus,

B(z) = C(z) / A(z)

It is well known that in the time domain, passing an impulse function through a filter yields the filter's impulse response. In the equation above, C(z)/A(z) can be viewed as just another filter. So to determine what b[n] is, all one needs to do is filter an impulse function by B(z)=C(z)/A(z). That is precisely what the deconv function does, via the command

q = filter(C, A, [1 zeros(1,nC-nA)]);

Unfortunately, if any of the roots of A(z) happen to fall outside of the unit circle, this results in an unstable filter, and this method breaks down.

A better method of deconvolution (but one which is far more computationally intensive) realizes that convolution is the equivalent to a matrix multiply in the form of Ax=b. This can be solved in MATLAB using the equation x=pinv(A)*b. For example:

x=[1 2 1]'; % make sure x and y are columns!!!

y=[1 2 3 4 5]';

z=conv(x,y); % now we will try to recover y

% convmtx generates the A matrix mentioned above

A=convmtx(x,length(z)-length(x)+1); %length(z)-length(x)+1==length(y)

y_recovered = pinv(A)*z

disp('norm of error = ')

norm(y_recovered-y)

Note that this method will break down in the presence of noise. If we simulate random noise being added to z by adding the line

z=z+[.9 .2 .4 .1 .31 .78 .21]';

Then the norm of the error rises to 0.8683 from 8.8596e-15. It can be shown that this form of deconvolution amplifies noise proportionally to the inverse of the singular values of A. In this case, the singular values of A are

>>svd(A)

ans =

3.7562

3.0873

2.1631

1.2120

0.4605

By inspection, we can see that one singular value is significantly closer to zero than the rest (which, when inverted, will amplify the noise in this system more than the rest). By specifying tolerance, an optional second argument to pinv, we can eliminate the effect of the smallest singular value:

y_recovered = pinv(A,0.5)*z

In this case, 0.5 was chosen because it is greater than the smallest singular value, but smaller than the rest. The norm of the error now drops back down to 0.4810, a decrease of almost 50%. Unfortunately, there are no clear cut rules to performing this sort of analysis, and only experience can help to determine which singular values should be kept and which should be thrown out.

6.3.4. How can I use xcorr to determine the amount of offset between one signal and another?

The following M-file demonstrates how to use xcorr to determine how much offset exists between two signals, x1 and x2:

t=0:.01:1.01;

x1=[t.^2]; % generate sample data

x2=[0 0 0 t.^2];

% x2 is delayed version of x1, delayed by 4 samples

xc=xcorr(x1,x2); % perform cross correlation

index=find(xc==max(xc));

% this is the index of the cross correlation where

% the cross correlation is at its maximum. I.e.

% this is where x1 and x2 line up the best.

middle=(length(xc)+1)/2;

% this is the middle element (since length(xc) is always % odd)

if index-middle>=0,

disp(['x2 is delayed from x1 by ' num2str(index-middle)...

' sample(s)']);

else

disp(['x1 is delayed from x2 by ' num2str(middle-index)...

' sample(s)']);

end