9/6 1996, by andersh@maths.lth.se. HTML-verson at http://www.maths.lth.se/matstat/andersh/matlabfaq.html

This was a FAQ once maintained by mwette@grover.jpl.nasa.gov (Matt Wette) and since a couple of years by andersh@maths.lth.se (Anders Holtsberg), and from now maintained by NOBODY since I've moved to a new job! Anybody may pick up this and continue!

comp.soft-sys.matlab Frequently Asked Questions

NOTE: See http://www.mathworks.com/faq.html (or ftp.mathworks.com with mirror novell.felk.cvut.cz) for The Mathworks FAQ-file on Matlab. There you will find much more detailed information and tips about Matlab as well as the main code archive. This shorter FAQ is mainly for pointers to things not found there, especially pointers to Mathworks' competitors and to free toolboxes. Also, at the end a section with code examples concerning the interesting sport of "vectorizing" is included for amusement.
  1. What is this newsgroup about?
  2. Where can I find information on Matlab and Simulink?
  3. Are there many Matlab-type environments?


  4. Are there any Matlab programs that do XYZ?
  5. What books and papers are there?


  6. Is there any automatic Matlab to C converter?
  7. When will Matlab for Linux arrive?
  8. How can I do a contour plot with unevenly spaced data?
  9. What about undocumented functions in Matlab?
  10. What is this `system_dependent' function?
  11. How do I fix printing on A4-paper?
  12. Why is OS/2 Warp's Win and Matlab 4.2 crashing?
  13. Why is the histogram function so slow?


  14. Why is my m-file so slow?
  15. How can I initialize a this low rank matrix easily?
  16. How can I load-from or save-to a file whose name is in a string variable?
  17. How can I store the result of `!ls *.dat' in a variable?
  18. How can I make a variable global from within a function?
  19. What is a fast way to compute a moving average?
  20. How many times does "a" occur in "x"?
  21. How can a large program block be commented out?
  22. What's the area of a polygon?
  23. How can I set all NaN's to 0?
  24. What's the inverse mapping of the sort order?
  25. How do I access the diagonal without a for-loop?
  26. How can I vectorize Gray-code conversion?
  27. How can I vectorize distance computations?


[1] What is this newsgroup about?

The newsgroup 'comp.soft-sys.matlab' is a forum for discussing issues related to the use of Matlab, the scientific calculation and visualization package from MathWorks Inc. This includes discussion of similar software packages like Xmath, Octave, RLab. Appropriate discussion in the group will include both general Matlab issues and platform-specific questions, and discussion comparing Matlab to other systems.

[2] Where can I find information on Matlab and Simulink?

Lots of information can be found at The Mathworks,


[3] Are there many Matlab-type environments?

Yes. Matlab competes in one way or another with the packages listed below. Since these programs are not oriented mainly towards symbolic manipulation we have left out Matematica, Maple, Derive and the likes. See sci.math.symbolic and comp.soft-sys.math.mathematica for discusson groups dedicated to those programs. Note though that Matlab may be sold together with a Maple kernel, so that one may do symbolic calculations from whithin Matlab.

==== First we have the commercial ones in alphabetical order. ====

`CLAM' from Scientific Computing Associates, Inc.
    246 Church Street, Suite 307
    New Haven, CT  06510
    Tel: 203-777-7442
    Fax: 203-776-4074

`Ctrl-C' from Systems Control Technology, Inc. is no longer supported since SCT does not exist. See Xmath below.

`Gauss' from ???.

`MATLAB' from The MathWorks, Inc.
    Cochituate Place
    24 Prime Park Way
    Natick, MA 01760
    Tel: 508-653-1415
    Fax: 508-653-2997.
    Email: info@mathworks.com

`O-MATRIX' from Harmonic Software, Inc. They say "Highly optimized functions make development of fast-executing applications easy. O-Matrix for Windows is a true 32-bit application with performance that far exceeds other 'matrix-based' languages". Futhermore "O-Matrix runs programs 150% to 200% faster than MATLAB(R)" and "O-Matrix for Windows is list priced at $395 and comes with an unconditional money-back guarantee. Group and academic discounts are available. All licences come with two years free technical support."
    Harmonic Software, Inc
    12223 Dayton Avenue North
    Seattle, WA 98133
    Tel: 206-367-8742
    Fax: 206-367-1067
    Email: harmonic@world.std.com


`Splus' from StatSci, A division of MathSoft, Inc.
    1700 Westlake Ave. N.
    Suite 500
    Seattle, WA 98109
    Tel: 206-283-8802
    Fax: 206-283-6310

    There is a very active user group (of mainly statisticians) 
    with a mailing list that can be found in the FAQ.

    FAQ: http://www.stat.math.ethz.ch/~roosen/S-faq_toc.html
         ftp.stat.math.ethz.ch  in  /pub/Doc  as  S-faq.*
    see also ftp://netlib.att.com/netlib/att/stat/info/proj.html

`Xmath' from Integrated Systems, Inc.
    3260 Jay St.
    Santa Clara, CA  95054-3309
    Tel: (408) 980-1500
    Fax: (408) 980-0400
    Email: xmath-info@isi.com
    WWW: http://www.isi.com     
SCT was bought out by ISI, so now the makers of XMATH/MATRIXX have all of the Ctrl-C customers and Ctrl-C is no longer supported.

==== Then we have the non-commercial ones in alphabetical order. ====

Check out the following page too, it is probably more complete on this point.


is being developed by Matt Wette (mwette@csi.jpl.nasa.gov). This will be released to COSMIC soon. It will provide data structures, conversion to C-code, and many other features. See
M.Wette, "Caesy: A Computer-Aided Engineering System"
Proc. 1992 Symp. on Computer-Aided Control System Design
Napa, CA, March 1992

is developed at Lawrence Livermore National Laboratories by Don Gavel. This is not publically available.

is written by M.Gerberg and E.J. Moore, University of New South Wales, Australia. It is available via anonymous ftp from
draci.cs.uow.edu.au  in  /netlib/matcalc/
csi.jpl.nasa.gov  in  /pub/matlab/matcalc/

is an interpreter and compiler, developed at Tokyo Institute of Technology. See
M. Koga and K. Furuta, "MaTX: A High-Performance Programming
Language (Interpreter and Compiler) for Scientific and
Engineering Computation," Proc. 1992 Symp. on Computer-Aided
Control System Design, Napa, CA, March 1992

is developed at the University of Waterloo by Grantham Pang (pang@excel2.uwaterloo.ca). This has the same command language as MATLAB, but includes a knowledge-based expert system development facility. It is available for academic and research users via anonymous. You'll need to get a program password from the author to operate it (no sources included). It's available via anonymous ftp from
excel2.uwaterloo.ca []  in  /pub/

See also

Pang, G.K.H.,"Knowledge-based Control System Design", in Recent Advances
in Computer-Aided Control Systems Engineering, Jamshidi, M and  Herget,
C.J. (ed.), Elsevier Science Publishers, 1992.

Pang, G.K.H., "A Knowledge Environment for an Interactive Control System Design Package", Automatica, Vol. 28. No. 3, pp. 473-491, May 1992.

You can download the Student Version of MathViews V1.71A (MATHSTUD.ZIP) from one of the mirror sites of
ftp.cica.indiana.edu in win3/programr.

"matvec is much more better than sum of maple+matlab+mathematica and it is free forever similar to linux it is written in c++ and yacc you should not miss it" says James McNalley! See

is written at the University of Texas (jwe@che.utexas.edu). It has very Matlab-like syntax and runs many m-files without modification.
ftp.che.utexas.edu  in  /pub/octave/
Linux binaries also at ftp.lightning.eee.strath.ac.uk  
   in  /pub/programs/../users/duncan/octave
mailing list for Octave: 

is written by Ian Searle (ians@eskimo.com), is free software (in the GNU copyleft sense). Although RLaB is Matlab-like, the language is _not_ a clone of Matlab. The language has a more C-like syntax, strings, and N-dimensional associative arrays in addition to the standard Matlab-like matrices. The source code is mainly C, and has been ported to most all Unix platforms, DOS, OS/2, and Apple Macintosh.
    evans.ee.adfa.oz.au  in      pub/RlaB
    csi.jpl.nasa.gov     in      pub/matlab/RLaB

 Unix: evans.ee.adfa.oz.au in pub/RLaB/Target-*
       Usually SunOS-4.x, Linux, and BSD-386.
       sunsite.unc.edu for the Linux version also.
 DOS:  ftp://oak.oakland.edu/SimTel/msdos/math/rlab117d.zip
       evans.ee.adfa.oz.au in area pub/RLaB/Target-DOS
 MAC:  ftp.stat.ucla.edu//apps/mac/rlab/rlab-117dx.hqx (2964K)
       info-mac//sci/rlab-117dx.hqx (2964K)

Unix-based, binaries for Linux and more in

  Author              Pekka.Janhunen@fmi.fi
  Distribution site   ftp.funet.fi:pub/sci/math/tela 
  Tela bugs           tela-bugs@fmi.fi
  Tela suggestions    tela-suggestions@fmi.fi
  Tela WWW-page       http://sumppu.fmi.fi/prog/tela.html

Formerly called CCALC. Syntax different from MATLAB but does similar things on vectors and matrices, and even does some symbolic calculations. Good graphics and runs under DOS. Very stable. Prentice Hall sells this with a book (ISBN 0-13-117441-X--or by calling 201-767-5937), but it is also available (without the manual but with a comprehensive help system) by anonymous FTP from
wuarchive.wustl.edu: /edu/math/msdos/calculus/cc4-9206.zip

`Yorick '
wuarchive.wustl.edu: /languages/yorick/yorick-1.0.tar.gz
sunsite.unc.edu: /pub/languages/yorick/yorick-1.0.tar.gz
sunsite.unc.edu: /pub/Linux/apps/math/matrix/yorick-1.0.tar.gz
etlib.att.com: /netlib/env/yorick-1.0.tar.gz
netlib2.cs.utk.edu: /env/yorick-1.0.tar.gz
sumex-aim.stanford.edu: /info-mac/dev/yorick-*
and its many mirrors 

==== Properties of some of the free programs. ====

The following is compiled from the net.

                    RLaB   Octave   SciLab   Tela
      DOS version    +      -        -        -
    documentation    +      +        -        ?
             fast    +      -        ?        +
Matlab compatible    -      +        -     converter
The plotting on all of them is not as good as with a commercial package. They either use Gnuplot or have some other builtin graphics.

from sundaram@news.cig.mot.com (Divya A. Sundaram) ... I am running Octave and SciLab under Linux (and also have matlab on the Windows box and on the Macintosh). I find Octave to be quite suitable for MOST stuff I used to do under Matlab (and find that most commands and syntax are the same or VERY similar). SciLab is something else. It is absolutely amazing and I have decided to spend some time learning it more thoroughly. I feel (personal opinion only) that it is a FAR more complete system than Octave or Matlab 4.0.

==== A proposed standard ====

There is an IFAC/IEEE-CSS Working Group developing standards and guidelines for these tools. A proposed standard command language was developed, is described in the document "Command Language Standard for CACSD Software" and is available from

    Magnus Rimvall
    Control Systems Laboratory, GE-CRD
    Schenectady, NY 12301

[4] Are there any Matlab programs that do XYZ?

A nice function is LOOKFOR, with the help of which you can search for a Matlab function with a keyword on your own computer. If there isn't there might be in one of The Mathworks' toolboxes, if you don't have them all. The Mathworks' toolboxes are the following, on which you can find more information at The Mathworks site.

Control System Toolbox
Image Processing Toolbox
MMLE3 Identification Toolbox
Model Predictive Control Toolbox
Mu-Analysis and Synthesis Toolbox
Nonlinear Control Design
Neural Network Toolbox
Optimization Toolbox
Robust Control Toolbox
Signal Processing Toolbox
Spline Toolbox
Statistics Toolbox
Symbolic Math Toolbox
System Identification Toolbox
Chemometrics Toolbox
Frequency Domain System Identification Toolbox
Hi-Spectm Toolbox

The Mathworks site is also a primary source for uploading and downloading free m-files. Note that NETLIB does not carry Matlab programs anymore, that archive was moved to The Mathworks site.

For graphics check out a web page that lists and provides descriptions and links to many freely available data analysis and graphic pages on the net:


Some major interesting matlab tools are the following.

From argus@shani.net (Joshua Margolin): Argus MeshMaker Pro is a graphical general purpose finite element and finite difference pre- and post-processing environment for numerical modeling. The software is "Model-Independent" and is being used as pre processor for FEA in MATLAB. If you are interested in additional information, including names of users using Argus MeshMaker in conjunction with Matlab please contact us. Argus Interware, Inc.

This toolbox contains functions useful to people interested in auditory/cochlear modeling, and using auditory models in their work. The goal of this toolbox is to provide several models of human auditory perception in an easy to use package. Includes Lyon's Passive Long Wave Cochlear Model, Correlogram generation and pitch modeling, Simple vowel synthesis, plus several more models.

"The Structural Dynamics Toolbox provides low cost, modular, and versatile access to methods in experimental and analytical structural dynamic modeling. A number of scientific functions implement standard and state of the art methods in three main areas experimental modal analysis, Finite Element analysis, Finite Element design and update."
Scientific Software Group
72-78 Grand Rue
92310 Sèvres (France)
Phone: (33) 1 45 34 23 91
Fax: (33) 1 45 07 08 06
E-mail: info@ssg.fr
"At the Division of Structural Mechanics and Solid Mechanics in Lund we have developed a finite element software as a toolbox to Matlab. The program is called CALFEM. It is used both in teaching and research at the departments."

Kirill Pankratov (kirill@slough.mit.edu) wrote: " As one example I can suggest my package DIME. It can compute embedded correlation dimension of time-series and also correlation dimension of a manifold in an arbitrary dimension. I posted it some time ago and also send it by request to many users (I will also put it on FTP site soon). However it computes only correlation dimension, not Housedorf, Lyapunov or other dimension estimates. Maybe somebody else has already done that ... "

A commercial box from Flexible Intelligence Group (FIGLLC@AOL.COM, http://home.aol.com/Figllc). Also, have a look at the two collections

GUI Maker 2.0 is a Graphical User Interface used to create your own GUIs. It should satisfy the needs of most levels (beginner/advanced) of MATLAB GUI GUI programming. This version allows you to create UI callbacks (the code that is executed when a UI object is clicked on) to be created simply, and in a fashion that can be re-edited by GUI Maker 2.0 either with the package or in the actual m-file.

A.Lotfi has developed a Fuzzy Inference Systems Toolbox. It is available via anonymous ftp from ftp.mathworks.com in
See also a commercial package at

Jyh-Shing Roger Jang has provided a few routines for demonstrating parameterizing membership functions (MF) and learning in fuzzy inference systems (FIS). The file fuzzdemo.tar.Z is available via anonymous ftp from

csi.jpl.nasa.gov  in  /pub/matlab/contrib/

LIPSOL is a Matlab-based package for solving linear programs by interior-Point methods. For computational efficiency it uses a Fortran package by Esmond Ng and Barry Peyton at ORNL to solve large sparse linear systems. LIPSOL has been tested on the Netlib set of linear programs and has effectively solved all 95 Netlib problems.

The m-files in this directory are used to create a draw-program-like interface for dealing with Matlab graphs. When you type "matdraw" at the Matlab prompt, they will create a palette with some standard draw tools and a suite of menus with a number of generally useful functions. This version of MatDraw is SHAREWARE. Read the license file for registration information. Author address is
kerog@sp.isl.secom.co.jp (Keith Rogers)

Apart from the Mathworks' own toolbox there are other out in space, e g

The MetaMatrix Toolbox extends MATLAB so that data sets with an unlimited number of dimensions can be created, manipulated, and displayed easily, both interactively and within scripts and functions. The toolbox consists of over thirty MATLAB-callable functions. Demo versions for various platforms (read README.1ST first) are available via
ftp.std.com in /vendors/metamat
gopher.std.com under "Shops on The World"

The ODE Suite is available by ftp from ftp.mathworks.com in the /pub/mathworks/toolbox/matlab/funfun directory. The directory also contains a README file with more information on the ODE Suite M-files, and odesuite.ps, the postscript version of a technical report describing the algorithms in detail. The ODE Suite requires MATLAB 4.2c.

Barry Wise's toolbox has now gone commercial. Barry has address EVTech@delphi.com. Is this the same as the following one?
Eigenvector Technologies
4154 Laurel Dr.
West Richland, WA 99352

Ahlea Systems Corp. is proud to announce the release of the Pattern Recognition Toolbox for MATLAB. Check out our home page at

Qplot is a GUI-driven plotting program for Matlab. Its not free, but its cheap. For more details see

The Real Time Toolbox is a package that enables Matlab to communicate with outside world in real time. Sampling fast signals up to 10 kHz, or even more with DMA, utilizes your data acquisition hardware to its limits. Many industry-standard data acquisition cards already supported, others are being continuously added Available for computers running Microsoft Windows only and requires Matlab 4.2 or higher.
Free demo version at novell.felk.cvut.cz ( 
e-mail: houska@control.felk.cvut.cz

The Signal Processing and Communications (SPC) software was designed to assist in the application of the signal processing concepts learned in the classroom. SPC is a window-based, user-friendly set of tools that allows the user to develop and to apply digital filters, analyze speech signals, and design basic signal models easily. Download from The Mathworks site or from
ftp.nps.navy.mil  /pub/ece  in the spctools directory
Rob Lake (rbl@hal.cwru.edu) said "... Lots of documentation. The only problem is that the .mex functions provided are for a Sun. As I recall, I e-chatted with Lt. Brown a few years ago and the problems with the Mac C compilers made porting the .mex files a bit challenging. ... If and when I get the whole kit converted, I'll post ..."

See Lester Ingber's Code, Simulated Annealing at

This is for a MacIntosh and it can be fetched as

SaGA in addition to its core spatial data interpolation and computational geometry routines contains many functions for dealing with points, lines and polygons. They range from relatively simple, like area and centroid calculations to quite sophisticated ones, like Boolean operation on pairs of polygons (intersections, unions. etc.) For the latter see a graphics example in the "gallery". SaGA is a shareware. See License file for registration information.

A toolbox including a subset of the statistical distribution functions as well as some functions for linear regression, model selection, bootstrapping, elementary tests, and graphics. Zero-cost alternative to Mathworks' Statistical toolbox.
ftp.maths.lth.se in /pub/transfer/andersh

The Styled Text Toolbox is a collection of tools which enables the user to mix fonts, text styles and mathematical constructs (superscripts, subscripts, integrals, special math characters, etc.) in a single styled text object. It consists of several m-files which are analogous to the MATLAB commands text, set, get, delete, print, title, xlabel, ylabel and zlabel. See

The Styled Text Toolbox by Douglas M. Schwarz is a collection of tools which enables the user to mix fonts (including Symbol) and styles in a single styled text object. It consists of several m-files which are analogous to the MATLAB commands text, set, delete, print, title, xlabel, ylabel and zlabel. Also included are a function to correct the position of styled text objects after axes modifications, two utility functions (used internally) and a demo. Download from
Another one is LINK, an application to simulate multi-font, multi-object text strings in MATLAB. Strings are entered in a LaTeX-like syntax and link formats and positions the result. This toolkit is also at

There are a number of wavelet toolboxes, see e g

W-transform toolboxat Argonne
info.mcs.anl.gov  in  pub/W-transform 

[5] What books and papers are there?

At The Mathworks site there are m-files that are used in the following books. The authors and full titles et c are also at The Mathworks site.

Control of Spacecraft and Aircraft
Computer-Based Exercises for Signal Processing Using MATLAB
Digital Control and Estimation: A Unified Approach
Numerical Methods for Physics Using MATLAB
Numerical Methods for Mathematics, Science and Engineering
Introduction to Linear Algebra
Templates for the Solution of Linear Systems ...
Digitale Signalverarbeitung ...

There are at least some Matlab introductions on the net;

'The Matlab Primer'
by Kermit Signon. It was briefly released to the net then apparently withdrawn and is now sold by CRC Press. Some copies can still be found by Archie (the file itself includes permission to freely copy and distribute it).
primer35.tex  at  math.ufl.edu  in  /pub/matlab

'Elements of Matlab'
ElementsOfMatlab.ps.Z  at  cs.colorado.edu  in  /pub/HPSC

See also a compiled list of books in the file

[6] Is there any automatic Matlab to C converter?

Mathworks is now selling its translator. Another alternative is MATCOM, which is a is freeware translator of MATLAB to C++. It seems to work pretty well, but can be confused by feval and gives up on eval. C++ compiler (Borland C++/Visual C++/DJGPP) on a PC compatible is required, or a UNIX system. For Borland C++/Visual C++ Windows is needed.

Home Page (now) -
Mirrors (in a few days) -
File name is matcom.zip, file size is 1,154,212 bytes. To unzip it use PKZip 2 or compatible.

[7] When will Matlab for Linux arrive?

Matlab 4.2c for Linux is released and selling!

For Linux there are also precompiled binaries for OCTAVE, RLAB, YORICK and PV-WAVE, all in
[8] How can I do a contour plot with unevenly spaced data?

Well, use GRIDDATA. However, since this is unlikely to work read what Kirill Pankratov says:

Surely GRIDDATA is not going to work for any realistic-size array. If your points X, Y compose a matrix, that is can be mapped into a rectangular grid, you can use a very good contouring package recently posted by Rich Pawlowich (I believe he can be reached at rich.ios.bc.ca) It is designed to handle distorted grids, fill between the contour lines and put nice labels. (A few months ago I posted my own routine to fill between contours. Yet Rich seems to found a more elegant solution, and moreover his package does many other beautiful things ...)

[9] What about undocumented functions in Matlab?

from Cleve Moler ...

Almost everything in the "demos" directory is not described in the User's Guide. There are lots of goodies there. In 4.0, the demos are 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 actually written after the User's Guide had been sent to the printer.

Then there are lots of undocumented stuff in the graphics objects too. Try

[10] What is this `system_dependent' function?

from John Little (w/editing) ...

`system_dependent' is an unpublished function that is used for a variety of crufty things. It will most certainly change from time to time and possible even go away completely. For anybody curious about it, here is what it does in MATLAB 4.0 on SPARCstations:

  system_dependent(1)     deals with the MATLAB-ACSL interface. 
                          ACSL is a simulation language that 
                          MATLAB can talk to. See ACSL.M for 
                          more information.

system_dependent(2,0) turns off command-line editing. system_dependent(2,1) turns it back on.

system_dependent(3) is unused.

system_dependent(4,i,j) is used to program the command-line editing keys. See CEDIT.M for more information.

system_dependent(5) enables core dumps in the event of seg faults. Normally MATLAB tries to catch seg faults and "continue".

system_dependent does different things in MATLAB 3.5 and other platforms.

[11] How do I fix printing on A4-paper?

From Andreas Payer (payer@cipserv1.physik.uni-ulm.de): The problem is, that MATLAB resets the printer driver back to its 'DefaultFigureSize' after each printing. My solution is a file 'startup.m' in my MATLAB home-directory with the following contents:

      'DefaultFigurePaperPosition',[0.5 0.5 11.1 7.7]);
You can play a little bit with the settings of the 'DefaultFigurePaperPosition' if you like, but with these settings it is guaranteed that the plot labels appear on the paper.

From Chritian Schmid (cs@esr.ruhr-uni-bochum.de): ...I had the same problem and solved it by adding the following statement: set(0,'DefaultFigurePaperType','A4'); to my matlabrc.m file. I found also, that you can retrieve all default setting keywords by entering getpref (undocumented, and no help available) and adding the prefix 'Default' to the keyword in the set(0,...)-statement.

[12] Why is OS/2 Warp's Win and Matlab 4.2 crashing?

There is a bug in the vwin.sys file in Warp's \os2\mdos directory. The updated file from IBM can be ftp'd from ftp.mathworks.com in /pub/mathworks/bin/os2warp

[13] Why is the histogram function so slow?

This is a tricky issue. A discussion including improved code can be found in



[14] Why is my m-file so slow?

The first and main trick is "vectorizing", i e avoiding for-loops. Do NOT write things like

    for i = 1:n               % 3 BAD examples  
        z(i) = x(i) * y(i); 

    for i = 1:n                 
        for j = 1:m
            if A(i,j) > B(i,j) 
               C(i,j) = D(i,j);
               C(i,j) = F(i,j);

    for i = 1:n-2               
        Z(i) = 4*X(i+2) + 2*X(i+1) + X(i);
but write instead
   z = x .* y;                % The GOOD versions

   J = A > B;
   C = D .* J + F .* (~J);
   W = [4 2 1];
   Z = filter(W,1,X);
   Z = Z(3:n);
Apart from looking much nicer it is incredably much faster for large vectors and matrices. Vectorizing complicated code is an interesting sport as you can see further down in this FAQ.

If you really must have for-loops then preallocate memory, it may be a large gain for large vectors, like in the following example.

    x = zeros(10000,1);  % Preallocation of memory!
    x(1) = rand;
    for i = 2:10000
       x(i) = ( 1 - 1.73*x(i-1))^2;
Tested on a sparc machine this runs on 2.6 seconds with the first line and 79.3 seconds without it!

Another time-saver is using sparse matrices if that is possible. As a last resort one may rewrite the innermost loops into cmex-files.

[15] How can I initialize a this 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))]

with the variant

    [a; b] * ones(1,m)
[16] How can I load-from or save-to a file whose name is in a string variable?

In Matlab 3.x you have to do something like

    name = 'xyz.mat';
    eval(['save ', name]);
    eval(['load ', name]);
In Matlab 4.x the first of the following lines is actually interpreted to mean exactly the same as the second one;
    myfunction qwerty
which means that "load(name)" may be used in Matlab 4.x. Now you figure out why the following statement gives a result that is intuitively weird at the first sight;
    sin pi

[17] How can I store the result of `!ls *.dat' in a variable?

    [stat, list] = unix('ls *.dat');
The variable `stat' contains the return status, the variable `list' contains the output.

[18] How can I make a variable global from within a function?

You can in Matlab 4. The following hack is from Laura Needles and Mike Kantner . Define the script file `mkglobal.m', containing

    function [] = mkglobal(var)
    % MKGLOBAL      mkglobal(var) - make var a global variable
    if ~exist('mkglobal_var'), mkglobal_1; end;
    mkglobal_var = var; mkglobal_2

Define the script file `mkglobal_1.m' as

    global mkglobal_var

Define the script file `mkglobal_2.m' as

    eval(['global ', mkglobal_var]);

[19] What is a fast way to compute a moving average?

A fast way of computing a moving average of "m" consecutive numbers in the row vector "x" of length "n" is

    z = [0 cumsum(x)];
    y = ( z(m+1:n+1) - z(1:n-m+1) ) / m;

[20] How many times does "a" occur in "x"?

Mauro Jorge Atalla asked if there was a clever vectorized way of counting how many times the components of a matrix are repeated in the matrix and wanted the result to return a matrix with rows of the form

    [number, number_of_times_it_appears_in_the_matrix]
A solution from Erik A. Johnson is
    sortM = sort(M(:));
    uniqueM = [diff(sortM);1] > 0;
    count = [sortM(uniqueM) diff(find([1;uniqueM]))];
Furthermore, if the elements are known to be integers then Hans Olsson's one-liner can be used:
[21] How can a large program block be commented out?

Use Tom L. Davis' trick.

    if 0,
       commented out code
That works however only if the parser doesn't complain about the commented out code. If that is the case you can ask kirill@slough.mit.edu (Kirill Pankratov) of his BLOCKCOM function.

[22] What's the area of a polygon?

If "x" and "y" are the coordinate points of a polygon (supposing the last coordinate is the same as the first one), then the shortest and fastest solution seen on the net so far to the problem of computing the area is the following one.

    area = abs(sum(diff(x).*(y(1:nl-1)+y(2:nl)))/2);

[23] How can I set all NaN's to 0?

If a matrix "x" contains NaN's they can be set to 0 by for example Jeffery Faneuff's solution

    x(isnan(x)) = zeros(size(x(isnan(x))));
    x(isnan(x)) = 0;  %ERROR
does not work. The Mathworks says it will work in the next release. By the way, figure out for yourself why the following program gives its interesting result!
    x = 1:5
    for i = 1:10, disp(x(ones(1,i))), end
[24] What's the inverse mapping of the sort order?

The following works for matrices that are sorted columnwise;

    [xs, i] = sort(x);
    [dummy, j] = sort(i);
However, if "x" is an ordinary vector of length "n" a nice alternative is
    [xs, i] = sort(x);
    j = 1:n;
    j(i) = j;
[25] How do I access the diagonal without a for-loop?

Use Loren Shure's trick for a n x n matrix "A",

    J = 1:n+1:n^2;
    D = A(J);            % Another form of "D = diag(A);".
    A(J) = zeros(1,n);   % This is not possible to do with "diag".
[26] How can I vectorize Gray-code conversion?

The question came up how to vectorize the following code.

   % convert from Gray code to binary code
   B = zeros(1,n);
   B(1) = G(1);
   for i=2:n
     B(i) = xor(B(i-1),G(i));
To this sjs@mod.dsto.gov.au (Stephen Searle) answered
   B = rem(cumsum(G),2);
[27] How can I vectorize distance computations?

Here is a tip from Frank Reine (reine@csd.de) for speeding up the distance calculations in for example clustering algorithms. Consider a NxK pattern matrix p with the patterns in its rows and a MxK centroid matrix w with cluster centers in the rows. Our goal is to calculate the NxM distance matrix d. Now, instead of using something like

for i = 1:M
   d(:,i) = sum((p-ones(N,1)*w(i,:))'.^2)'
as it is done e.g. in the fuzzy toolbox, try using
s2 = sum(p'.^2)';
w2 = sum(w'.^2);
d = s2(:,ones(1,M)) - 2*p*w'+ w2(ones(N,1),:);
as a fully vectorized version. There is a significant improvement in execution speed, especially for large K.