Languages‎ > ‎Matlab‎ > ‎

Matlab FAQ

Contents

  1. 1 Basics
    1. 1.1 Why does MATLAB only calculate to 4 significant digits?
    2. 1.2 Why does the transpose operator take the complex conjugate?
    3. 1.3 How can I detect NaN values in a matrix or vector?
    4. 1.4 How can I make MATLAB use the full window width for displaying matrices?
    5. 1.5 How do I comment out a large block of code?
    6. 1.6 How do I save default settings across sessions?
    7. 1.7 How can I find local maxima in a vector array?
    8. 1.8 Why is 6*i not complex in my program?
    9. 1.9 How can I modify the MATLAB path?
    10. 1.10 How can I make a standalone executable from my MATLAB code?
  2. 2 Programming
    1. 2.1 Can I read a text file with a certain format?
    2. 2.2 Why are global variables bad?
    3. 2.3 What about this logical array business?
    4. 2.4 Huge memory waste using array of structs?
    5. 2.5 Why is my MEX file crashing?
    6. 2.6 How can I create variables A1, A2,...,A10 in a loop?
    7. 2.7 Do boolean operators short-circuit?
    8. 2.8 How do I fix "Out of Memory" problems?
    9. 2.9 How do I dynamically generate a filename for SAVE?
    10. 2.10 What's the difference between M-files, Pcode, and MEX files?
    11. 2.11 Can MATLAB pass by reference?
    12. 2.12 How can I process a sequence of files?
    13. 2.13 How can I pass additional parameters into a "function function" like ODE45, QUAD, FSOLVE, FMINCON, GA, etc?
    14. 2.14 Why does MATLAB clear the breakpoints I've set in my M-file?
    15. 2.15 Why do I receive an error about an undefined variable or the recursion limit when calling ODE45?
  3. 3 Graphics
    1. 3.1 How do I adjust the fontsize of a ticklabel?
    2. 3.2 Can I create a pi/sigma/superscript in my ticklabels?
    3. 3.3 Can I open multiple files using uigetfile?
    4. 3.4 I want to use a scrollbar to scroll my edit boxes/buttons
    5. 3.5 How can I rotate ticklabels?
    6. 3.6 How can I display data in a grid like Excel?
    7. 3.7 How can I write a title or text with multiple lines?
    8. 3.8 How can I use a common color scale among several images?
    9. 3.9 How can I set default handle graphics properties?
    10. 3.10 How can I modify the default background color used for histograms?
    11. 3.11 How can I draw more than two lines with plotyy?
    12. 3.12 Is there a command available for plotting an arrow on a graph?
    13. 3.13 Why does movie(M,1) display the movie M twice?
    14. 3.14 How can I set the focus in my GUI?
    15. 3.15 How can I add text labels to data points?
  4. 4 Math/Algorithms
    1. 4.1 Why is 0.3-0.2-0.1 not equal to zero (or similar)?
    2. 4.2 How does the backslash operator work? What does it do?
    3. 4.3 How does one compute a factorial?
    4. 4.4 How can one accurately compute ratios of factorials?
    5. 4.5 How can I fit a circle to a set of XY data?
    6. 4.6 Why does MATLAB return an complex number for (-8)^(1/3)
    7. 4.7 Can I compute the DFT of an irregularly-sampled signal?
    8. 4.8 How can I efficiently do row-wise vector-matrix multiplication?
  5. 5 Installation, Crashes, Platform-Specific Issues
    1. 5.1 MATLAB 5.3 won't run on my linux system.
    2. 5.2 Why do I get a segfault after compiling correct MEX files under linux?
    3. 5.3 Why does MATLAB 6.0 crash on my Pentium 4?
    4. 5.4 How can I make MATLAB 6.0 (R12) open without the GUI?
    5. 5.5 Why does MATLAB 6.0 crash under Redhat 7.0?
    6. 5.6 Why can't I type into the command window?
    7. 5.7 How do I release a MATLAB license?
    8. 5.8 Is MATLAB optimized for the Pentium IV?
    9. 5.9 Why doesn't Ctrl-C interrupt execution of my m-file?
    10. 5.10 Why does MATLAB 7.0 (R14) crash on startup on my AMD Sempron or AMD Turion machine?
  6. 6 Toolboxes, Software Archives, Books, and Other Resources
    1. 6.1 Where can I find archives of user-contributed MATLAB software?
    2. 6.2 Where can I find a package to perform a specific task?
    3. 6.3 What textbook would you recommend for learning MATLAB?
    4. 6.4 Where can I find MATLAB Style Guides or Coding Standards?
  7. 7 Simulink
    1. 7.1 How do I insert a Simulink model into an MS Office Document?
    2. 7.2 What are best practices for modeling communications systems with Simulink?
  8. 8 Miscellaneous
    1. 8.1 Can I use MATLAB to interface to an RS232 serial port?
    2. 8.2 I've seen system_dependent on the newsgroup before. What does it do?
    3. 8.3 Why does bench run so much slower in MATLAB 6.x than in 5.x?
    4. 8.4 What is vectorization?
    5. 8.5 What is Acklamization?
    6. 8.6 Why does MATLAB needlessly access the floppy drive?
    7. 8.7 How do I run MATLAB in batch mode?



Basics

Why does MATLAB only calculate to 4 significant digits?

It doesn't. It uses full double-precision floating point numbers to calculate everything. By default it only prints a few decimal places to the screen. You can change this using the command format long. Type help format for more information.

Why does the transpose operator take the complex conjugate?

When performing linear algebra operations on complex matrices, it is almost always the complex conjugate transpose (also called the Hermitian transpose) that is needed (see Gilbert Strang's linear algebra book for discussion- page 293 in edition 3). The bare apostrophe is an operator that takes the complex conjugate transpose. The non-conjugating transpose operator is a period followed by an apostrophe. Type help punct for more info.

>> A'     % complex conjugate transpose
>> A.' % transpose

How can I detect NaN values in a matrix or vector?

By definition, NaN is not equal to any number, not even NaN itself. Therefore there are two ways to detect NaN values:

 % Generate sample data
x = rand(1, 10);
x(x > 0.5) = NaN;
 % Find NaN values in two different ways
y1 = isnan(x) ;
y2 = (x ~= x) ;

How can I make MATLAB use the full window width for displaying matrices?

Bob Gilmore writes:

In R12 (MATLAB 6.0), this can be controlled via a preference. Select the File | Preferences... menu item, and select Command Window in the Preferences dialog that appears. In the Display section, there's a checkbox labeled Limit matrix display width to eighty columns. Unchecking that box allows matrix displays to make full use of the Command Window's width. [Unchecked is the default.]

Starting with MATLAB R12.1, users can access the current command window size using the root property CommandWindowSize. That is, sz=get(0, 'CommandWindowSize'). In R12.0, there is no way to do this unless you call undocumented C functions from a MEX file.

How do I comment out a large block of code?

Starting in MATLAB 7 (R14), the syntax is:

%{
Stuff to be commented out
%}

If you have an older version, the built-in editor in MATLAB 6.0 has a block-comment feature, which will simply put a comment character on each line. Or you can use matlab-mode for Emacs, which supports this as well.

If you are using an even older version, use this:

if 0
commented out code
end

This is not the best solution, since parse errors inside that block will cause an error. But it's better than sticking comment characters in from of every line.

How do I save default settings across sessions?

The key is to create a STARTUP.M file. Look at the online help for more detailed instructions specific to your operating system.

How can I find local maxima in a vector array?

You can use the following one-line function to determine the indices of the local maxima.

function index = localmax(x)
index = find( diff( sign( diff([0; x(:); 0]) ) ) < 0 );

Why is 6*i not complex in my program?

You may have overwritten the variable i with a number earlier in your program or session. MATLAB will use the new value instead of treating i as sqrt(-1) in this case. Five ways to ensure that you receive a complex result are:

  • Use the syntax 6i; MATLAB always interprets this as 6*sqrt(-1)
 y = 6i;
  • Redefine i back to sqrt(-1)
 i=sqrt(-1)
y = 6*i;
  • Clear your redefinition of i
 clear i
y = 6*i;
  • Use j instead of i
 y = 6*j;
  • Use the COMPLEX function
 y = complex(0, 6);

How can I modify the MATLAB path?

Easiest solution: use the PATHTOOL GUI. Or if you want command line access:

Suggested by Joshua Stiff: You can use addpath to add directories from the command line, and path2rc to write the current path back to `pathdef.m'. If you do not have write permissions for `pathdef.m', path2rc can write to a different file, which you can execute from your `startup.m'.

How can I make a standalone executable from my MATLAB code?

To generate a standalone executable that you can execute outside MATLAB or on a computer without MATLAB, you will need to use the MATLAB Compiler.

http://www.mathworks.com/products/compiler/

The section titled "Deployment Process" in the documentation for this product gives instructions on what steps you need to perform to run the executable on a machine that does not have MATLAB installed.

Programming

Can I read a text file with a certain format?

Yes. If the file has nothing but numbers separated by whitespace, and has a constant number of columns through the entire file, you can just type load myfile.txt.

The function DLMREAD is more flexible and allows you to read files with fields delimited by any character.

The function TEXTREAD is more flexible still and allows you to skip lines at the beginning, ignore certain comment lines, read text as well as numbers, and more. Type help textread for more info.

If none of these suit your needs, you can always use the low-level file I/O functions FOPEN, FREAD, FSCANF, FGETL, FSEEK and FCLOSE to read the data however you would like.

Why are global variables bad?

Urs (us) Schwarz writes in [1] (http://groups.google.com/group/comp.soft-sys.matlab/msg/b16db3c8d8c92223?dmode=source) (lightly edited):

I'll always fondly remember the outburst of the notorious and seasoned user Lars Gregersen to a recent poster (that most likely started this question) and will give it on to my students:

The short answer is: Don't use global variables.

The longer answer is: Don't use global variables unless you absolutely have to.

Now,

1) Using globals is perfectly okay (that's why they here on first place), just like for's and while's and other intelligible 2nd generation computer language constructs (that MATLAB is built on).

2) Using globals is a blasphemy from a programmer's point of view because it shows that she/he didn't think ahead but was rather sloppy... and just kept adding on those never-ending "important set up" parameters that she/he needed to use by all the axes - or whatever - of a one single project ...

3) Using globals is a problem in terms of bookkeeping if you end up having zillions of them hovering around in your workspace, and start having problems because one <my_par> from func1 is mixed up with <my_par> from func2 ... and <whos global> shows you 20 pages worth of variables ...

4) Using globals won't work in certain MATLAB contexts, such as GUI callbacks

[Respectfully edited]

Hence, eventually collecting your globals into a struct (i.e., cleaning up your toolbox) and passing it on as a parameter of your functions is the most economic way to program in MATLAB ... and it shows your intelligence, to boot.

What about this logical array business?

From the Getting Started book:

The logical vectors created from logical and relational operations can be used to reference subarrays. Suppose X is an ordinary matrix and L is a matrix of the same size that is the result of some logical operation. Then X(L) specifies the elements of X where the elements of L are nonzero.

To remove the logical flag from an array, don't add 0 as suggested by help logical in MATLAB 5.x. This actually adds zero to each element of the matrix. Instead, use a + in front, as in +x. This is a solution given in help logical in MATLAB 6.

Huge memory waste using array of structs?

The following example was posted to the newsgroup:

I've discovered to my horror that structs take up an obscene amount of overhead (I'm running version 5.3.1.29215a (R11.1) on a Dec ALPHA). I have a set of 10,242 observations, each consisting of 3+13=16 fields, which have 3*27 + 1*13 = 94 values. So the total size in bytes should be 10,242 * 94 * 8 bytes/double = 7,701,984.

I have this stored in a 1 x 10242 data structure, and when I issue the whos command, it tells me that the data now takes up 27,367,136 bytes!

Cris Luengo answers:

My guess would be that a structure contains MATLAB arrays. Each array has some overhead, like data type, array sizes, etc. In your second implementation (index using data.latitude(observation)), there are 10,242 times less arrays allocated. Note that in your data, for each observation, you have 13 arrays with one value. I don't know how large the matrix header exactly is, but it is a waste putting only a single value in it!

I think Cris has hit it exactly. Every MATLAB matrix has an overhead of ~100 bytes, even matrices with a single element. In this example, there are 16 fields * 10242 elements = 163872 matrices. Each one of these matrices adds an additional 100 bytes, for 16.4Mbytes in pure overhead. This still comes up a little short of the amount reported, but it is fairly close.

It is much more efficient, both for storage and computation, to use a struct of arrays rather than an array of structs.

Why is my MEX file crashing?

Memory errors are one likely reason. Greg Wolodkin suggests the debug memory manager:

The platform-independent way to use the debug memory manager is to set the environment variable MATLAB_MEM_MGR to contain the string "debug".

On Windows:

 C:\> set MATLAB_MEM_MGR=debug
C:\> matlab

On Unix with csh or tcsh:

 % setenv MATLAB_MEM_MGR debug
% matlab

On Unix with sh or bash:

 $ MATLAB_MEM_MGR=debug matlab

The debug memory manager cannot catch your code the instant it writes out of bounds (tools like Purify can do this but the performance hit they induce is quite painful). What it will catch is that in general, when you write outside of one memory block you end up writing into another, corrupting it or (in the case of the debug memory manager) hopefully corrupting only a guard band. When you later free the memory, we can tell you that you walked off the end of the block and corrupted the guard band.

How can I create variables A1, A2,...,A10 in a loop?

Don't do this. You will find that MATLAB arrays (either numeric or cell) will let you do the same thing in a much faster, much more readable way. For example, if A1 through A10 contain scalars, use:

A = zeros(1,10);        % Not necessary, just much faster
for i=1:10
A(i) = % some equation
end

Now refer to A(i) whenever you mean Ai. In case each Ai contains a vector or matrix, each with a different size, you want to use cell arrays, which are intended exactly for this:

for i=1:10
A{i} = 1:i;
end

Note that each A{i} contains a different size matrix. And be careful to use the curly braces for the subscript!

Another way to have your cake and eat it too is to use structures instead of cell arrays. The fields of the structure can be the variable names you want. And you can index into them with dynamic field references. For example:

names = {'fred' 'sam' 'al'};
for ind = 1:length(names)
s.(names{ind}) = magic(length(names{ind}));
end

In this case, you end up with the variable s, a structure, containing fields specified by the strings stored in the cell array names.

Now, if you still really want to create variables with dynamically generated names, you need to use EVAL. With EVAL, you use MATLAB commands to generate the string that will perform the operation you intend. For example, eval('A=10') has the same effect as A=10, and eval(['A' 'B' '=10']) has the same effect as AB=10, only the EVAL method executes much more slowly. So in a loop, you could use:

for i=1:10
eval(sprintf('A%d = [1:i]', i));
end

Notice how much more obfuscated this is. In addition, this can cause difficult-to-troubleshoot problems in your code, particularly if you try to dynamically create a variable with the same name as a function:

function y = mysin(x)
eval('sin = 5;');
y = sin(x);

Calling this function with "y = mysin(1)" will not return y = 5 (the first element of the sin variable created by EVAL) -- it will return the sine of 1, because when the function was parsed there was no variable named sin and so the usage of sin on the last line was parsed as a call to the built-in SIN function. The fact that a variable named sin existed at runtime is irrelevant; the parsetime "decision" takes precedence.

Repeat: don't create variables at runtime using EVAL unless you have a very good reason, such as someone gives you a MAT file with 2000 variables named A1428, for example. Even in that case, you can avoid EVAL:

% Assume the MAT-file example1.mat contains 2000 variables, A1 through A2000
S = load('example1.mat');
% S is now a struct array with 2000 fields, S.A1 through S.A2000.
% To access A1428, use:
x1 = S.A1428;
% If the "index" of the variable you want to access is stored in a variable:
k = 1428;
x2 = S.(sprintf('A%d', k));
x3 = S.(['A', num2str(k)]);

Do boolean operators short-circuit?

In many programming languages, boolean operators like AND and OR will stop evaluating as soon as the result is known. For instance,

1 | error('Short-circuit')

would never get to the error part, since the 1 is always true.

MATLAB versions >= 6.5 include the new short-circuiting logical operators || and &&. Use these for all condition tests in loops and similar, and use the old | and & for element-by-element logical operations. You can find details here (http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/logicaloperatorsshortcircuit.html).

In older versions of MATLAB, the boolean operators | and & are only short-circuit evaluated inside the conditions of IF and WHILE statements. In all other contexts, all parts of the conditional are evaluated.

How do I fix "Out of Memory" problems?

A frequent variant of this question is: "I have 512M of RAM, and 2G of swap space. Why can't I create this 200M matrix?"

Simple answers first: Remember that double precision floats take up 8 bytes. So a million element vector takes up 8Mbytes. Be sure you're estimating properly.

Many operations need to create duplicate matrices. For example, B=inv(A.') must create a tempory variable the same size as A to hold the transpose, and B is again, the same size as A.

If you're sure your matrices are reasonably sized, then read all of TMW Tech Note 1106, a great reference: http://www.mathworks.com/support/tech-notes/1100/1106.shtml

How do I dynamically generate a filename for SAVE?

You're probably trying

fname = 'foobag';
save fname variable;

To do this correctly, you need to use the "functional" form of save:

fname = 'foobar';
save(fname, 'variable');

In fact, it is true in general that the following two lines are equivalent:

command str1 str2 str3
command('str1', 'str2', 'str3')

This allows one replace any or all of the parameters with dynamically generated strings. This is also useful in commands like PRINT, LOAD, CLEAR, etc.

What's the difference between M-files, Pcode, and MEX files?

Suggested by Joshua Stiff:

  • M-files are plain ASCII text that is interpreted at run time. Actually it is parsed once and "just-in-time" compiled, but this is transparent to the user. Use M-files for most of your MATLAB development, and for platform independence and maintainability.
  • Pcode is a preparsed and encoded version of the M-file. Since it is preparsed, it saves on the load time of the function. This is most likely not an issue except for very large M-files, since most are parsed only once anyway. Pcode also lets you hide the source code from others. Careful, there is no way to convert Pcode back to the M-file source. Pcode is platform independent.
  • MEX files are native C or C++ files that are dynamically linked directly into the MATLAB application at runtime. They must be compiled for each hardware architecture on which they are to be run. MEX files have the potential to crash the MATLAB application, but rather large speed gains are possible, depending on the algorithm.

Can MATLAB pass by reference?

This is really two questions in one. One is "Can I modify a function's input argument?" This would save memory and simplify programming in some cases. The answer here is "NO". If you modify the input argument of a function, all you do is modify a copy of the argument local to the function. The only way to modify variables from a function is to return the result when finished, as in

bigstruct = addelement(bigstruct, 5);

The other question is: "Pass by value wastes memory and time, since copies of variables are made. How can I fix this?" Here, the answer is "Your assumption is flawed, you don't need to." MATLAB uses a scheme called "copy-on-write" to optimize this sort of thing. Basically, data is shared between variables whenever possible, and a true copy is made only when one of the variables is modified. So although MATLAB's calling convention appears to be pass-by-value, if you don't modify the input variables, the data is never copied.

How can I process a sequence of files?

An example of how to process a sequence of files has been added to this section of the documentation (http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/import_export/br5wz4t.html#br7q_u6) with release R2009b of MATLAB. For earlier releases of MATLAB, you can refer to the information below.

If the files that you want to process are sequentially numbered, like "file1.txt", "file2.txt", "file3.txt", etc. then you can use SPRINTF or STR2NUM to create the filename and LOAD, IMREAD, FOPEN, etc. to retrieve the data from the file:

% Read files file1.txt through file20.txt, mat1.mat through mat20.mat
% and image1.jpg through image20.jpg
for k = 1:20
matfilename = sprintf('mat%d.mat', k);
matdata = load(matfilename);
  jpgfilename = strcat('image', num2str(k), '.txt');
imagedata = imread(jpgfilename);
  textfilename = ['file' num2str(k) '.txt'];
fid = fopen(textfilename, 'rt');
textdata = fread(fid);
fclose(fid);
end

If instead you want to process all the files whose name matches a pattern in a directory, you can use DIR to select the files:

jpegFiles = dir('*.jpg');
for k = 1:length(jpegFiles)
filename = jpegFiles(k).name;
data1 = imread(filename);
end

How can I pass additional parameters into a "function function" like ODE45, QUAD, FSOLVE, FMINCON, GA, etc?

The term "function functions" refers to functions in MATLAB and the toolboxes that accept a function (usually a function handle) and evaluate that function repeatedly during the course of their work. Some examples of "function functions" are:

  • the ordinary differential equation solvers like ODE45, ODE23, etc.
  • the integration functions like QUAD and QUADL
  • the optimization functions in the funfun directory in MATLAB, like FMINSEARCH and LSQNONLIN
  • the optimization functions in the Optimization Toolbox, like FMINCON, FSOLVE, and LSQCURVEFIT
  • the optimization functions in the Genetic Algorithm and Direct Search Toolbox, like GA and PATTERNSEARCH

There are several documents on The MathWorks support website that shows examples of how to pass additional parameters to the functions used by the "function functions".

This information has also been incorporated into the documentation in recent versions of MATLAB and the toolboxes:

Why does MATLAB clear the breakpoints I've set in my M-file?

When a function is cleared from memory using the CLEAR function, breakpoints in that file are also cleared. That means that if you execute code including the statement "clear functions", "clear <the name of your function>", or "clear all", your breakpoints will be cleared.

If you want to have your program stop execution and enter debug mode regardless of whether or not you have cleared it, insert a call to the KEYBOARD function into the code at the location where you want to enter debug mode. This will not be cleared by the CLEAR function and will cause MATLAB to enter debug mode when the KEYBOARD function is called.

Alternately, you can use the "Stop if Errors/Warnings" item under the Debug menu in the MATLAB Editor to cause MATLAB to enter debug mode whenever the code you're running throws an error that is not caught by a TRY/CATCH block, whenever it throws an error that is caught by a TRY/CATCH block, whenever it throws a warning, or whenever the value of a variable becomes Inf or NaN. You can find more information on this item in the documentation (http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/matlab_env/bq4hw4g-1.html).

Why do I receive an error about an undefined variable or the recursion limit when calling ODE45?

One common cause of an "Undefined function or variable" error or an error about the RecursionLimit being exceeded when using an ODE solver like ODE45 is that the function being called by the ODE solver itself contains the call to the ODE solver. For instance, if your code is: function dy = myodefunction(t, y) dy = [y(2); 2*t];   y0 = [0; 1]; tspan = [0 10]; [t, y] = ode45(@myodefunction, y0, tspan); If you call myodefunction with no inputs, you will receive an error on the second line, where MATLAB tries to use t and y to define dy. If you call myodefunction with two inputs, it will proceed without error to the ODE45 call. ODE45 will call myodefunction with two inputs, and that call will proceed without error to the ODE45 call. This process will repeat until ODE45 has recursively call myodefunction a number of times equal to the root RecursionLimit property, at which point MATLAB will throw an error.

To avoid these errors, do not include the call to the ODE solver inside your ODE function (the function you pass to the ODE solver as the first input argument.) Instead, define the ODE function in a subfunction or as a separate M-file and use that in your ODE45 call. The subfunction approach is: % begin myodefunction.m function [t, y] = myodefunction y0 = [0; 1]; tspan = [0 10]; [t, y] = ode45(@myodesubfun, y0, tspan);   function dy = myodesubfun(t, y) dy = [y(2); 2*t]; % end myodefunction.m The separate M-file approach is: % begin myodefunction.m function [t, y] = myodefunction y0 = [0; 1]; tspan = [0 10]; [t, y] = ode45(@myodeseparatefun, y0, tspan); % end myodefunction.m   % begin myodeseparatefun.m function dy = myodeseparatefun(t, y) dy = [y(2); 2*t]; % end myodeseparatefun.m

Graphics

How do I adjust the fontsize of a ticklabel?

The ticklabel gets its properties from the axis to which it is attached. So set(gca, 'fontsize', 14) should do the trick. Type get(gca) to see what else you can set.

Can I create a pi/sigma/superscript in my ticklabels?

Not directly... MATLAB does not interpret TeX strings in ticklabels. You can play games with placing text by hand. See the MathWorks solution for some ideas of how to work around this.

There are also some free third-party software packages you can use to accomplish this.

Doug Schwarz has written a Styled Text Toolbox that does this. It is freely available at: http://www.frontiernet.net/~dmschwarz/stextfun/index.html

Can I open multiple files using uigetfile?

As of MATLAB 7.0 (R14), you can use the 'MultiSelect' parameter with UIGETFILE to allow the selection of multiple files. If you are using a version of MATLAB prior to version 7.0, you can use the `uigetfiles.dll' submission on the MATLAB Central File Exchange to do this on a Windows platform. This file is located here (http://www.mathworks.com/matlabcentral/fileexchange/Files.jsp?type=category&id=&fileId=331).

I want to use a scrollbar to scroll my edit boxes/buttons

Sorry, there's no easy solution. MATLAB does not support hierarchical figures, so you can't have a container control holding your controls. If you really need this you'll have to create your own, using the callbacks from the scrollbar to modify the position properties of your controls.

Ghassan Hamarneh writes:

What I would do is to add 2 pushbuttons to the figure: one at the top right and another at the bottom right and use these buttons to control the vertical scroll of the content of the figure. (surely you can add another 2 horizontal pushbuttons, lower left and lower right).

Whenever any of these buttons is pressed, you loop over all the controls except the two pushbuttons, and increment/decrement the vertical/horizontal postition value of each control. Something like this:

 % fig_handle is the handle of the figure containing the UI controls
% pushb1_handle, pushb2_handle are the handles of the pushbuttons
% described above
 % find handles of all the controls
all_handles=findobj(fig_handle);
 % exclude the handles of the 2 pushbuttons and the figure itself
move_handles=setdiff(all_handles, ...
[fig_handle, pushb1_handle, pushb2_handle]);
 % loop over the remaining handles and change their positions
for k=1:length(move_handles)
set(move_handles(k),'position', ...
(get(move_handles(k),'position'))-[0 0 0 10]);
end

How can I rotate ticklabels?

You can't do that directly but there are some community-generated solutions in File Exchange. See Format Tick Labels (http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=15986) as an example.

How can I display data in a grid like Excel?

If you simply want to edit the matrix as if it were an Excel spreadsheet, you can use the builtin Array Editor. Type openvar(my_var) at the command prompt, or double click on the variable in the Workspace Browser.

How can I write a title or text with multiple lines?

This can be done using a cell array of strings:

 title({'First line','Second Line'})
text(0.5,0.5,{'First line','Second Line'})

How can I use a common color scale among several images?

One way to do this is to insert a CAXIS command in your plotting function/script. For this to work well, you first need to have a first look at all of your data to determine what are the minimum and maximum values over the entire set of images. For example, if the overall minimum value amongst all images is 40 and the overall maximum is 256, you may issue the command "caxis([40 260])" for each image.

Tech note 1215, at http://www.mathworks.com/support/tech-notes/1200/1215.shtml, addresses a related question, namely "How can I use multiple colormaps in a single figure". As a bonus, it includes a thorough discussion of colormaps in general.

How can I set default handle graphics properties?

There are probably several hundred of these default handle graphics options. Rather than trying to remember any particular one, the best thing is to learn the general principle behind all of these default handle graphics properties. The basic call to insert into your startup.m file is :

 set(0,'DefaultObjectnamePropertyName',Value)

For line objects, here are a few examples:

set(0,'DefaultLineMarkerSize',12);
set(0,'DefaultLineMarker','d');
set(0,'DefaultLineLineWidth', 2);

Similarly, you can use these statements for axes objects:

set(0,'DefaultAxesLineWidth', 2);
set(0,'DefaultAxesXGrid','on');
set(0,'DefaultAxesTickDir','out');
set(0,'DefaultAxesTickLength',[0.015 0.015]);
set(0,'DefaultAxesFontName','Arial')

For more details, do a full text search for 'Defining Default Values' in the R12 online help, and click on the very first hit. Also see the following entries in the R12 online help:

  • Graphics Object Hierarchy
  • Types of Graphics Objects

How can I modify the default background color used for histograms?

A histogram is made up of patch objects. The trick is to modify the FaceColor property of these patches. A short example follows:

x=rand(400,1);
hist(x); % Default facecolor is blue
h=get(gca,'Children');
set(h,'FaceColor', 'm'); % magenta facecolor

% Draw only the edges of the bars making up the histogram
set(h,'FaceColor', 'none');

How can I draw more than two lines with plotyy?

You can use the axes' handles to plot additional lines, as follows:

x1 = (1:10)';  x2 = x1;  y1 = x1; y2 = x1.^2;
%Plot one line against each of the left and right y-axis
[ax, h1, h2] = plotyy(x1,y1,x2,y2);
%Plot additional line against the left y-axis
x3= x1; y3 = y1 + 3;
h3 = line(x3,y3,'Parent', ax(1), 'Color',get(h1,'Color'));

%Plot additional line against the right y-axis
x4= x1; y4 = y2+3;
h4 = line(x4,y4,'Parent', ax(2), 'Color',get(h2,'Color'));
set(ax,'YLimMode','auto','YTickMode','auto')

Is there a command available for plotting an arrow on a graph?

A user-contributed m-file (arrow.m) is available at http://www.mathworks.com/matlabcentral/fileexchange/Files.jsp?type=category&id=&fileId=278

Also look at arrow3.m at http://www.mathworks.com/matlabcentral/fileexchange/Files.jsp?type=category&id=36&fileId=1430

Why does movie(M,1) display the movie M twice?

Quoting from the MATLAB 6.1 online helpdesk: The movie function displays each frame as it loads the data into memory, and then plays the movie. This eliminates long delays with a blank screen when you load a memory-intensive movie. The movie's load cycle is not considered one of the movie repetitions.

How can I set the focus in my GUI?

You can't. One hopes that The MathWorks will include this often-requested feature in a future, but there is no guarantee.

Related to this, changing the stacking order of your GUI elements might allow you to set the tab order, but this seems to not always work. GUIDE in MATLAB version >= 6.5 includes a Tab Order Editor, which does a better job at this.

How can I add text labels to data points?

The text command can be used in a vectorized form to automatically add text labels wherever needed. Say you have a matrix D, where the first column contains X coordinates and the second column contains Y coordinates. Then us illustrates:

plot(D(:,1),D(:,2),'+-');
n=num2str(D,'%5.3f/');
n=n(:,1:end-1); % Just to remove the trailing slash
text(D(:,1),D(:,2),n);

Math/Algorithms

Why is 0.3-0.2-0.1 not equal to zero (or similar)?

(The above example returns -2.7756e-17.) Jason Bowman writes:

As is mentioned all the time in this newsgroup, some floating point numbers can not be represented exactly in binary form. So that's why you see the very small but not zero result. See EPS.

[...]

The difference is that 0:0.1:0.4 increments by a number very close to but not exactly 0.1 for the reasons mentioned below. So after a few steps it will be off whereas [0 0.1 0.2 0.3 0.4] is forcing the the numbers to their proper value, as accurately as they can be represented anyway.

Urs (us) Schwarz elaborates:

Watch Jason's response unfolding:

   a=[0 0.1 0.2 0.3 0.4];
b=[0:.1:.4];
   as=sprintf('%20.18f\n',a)
as =
0.000000000000000000 % ==
0.100000000000000010 % ==
0.200000000000000010 % ==
0.299999999999999990 % ~= bs !
0.400000000000000020 % ==
   bs=sprintf('%20.18f\n',b)
bs =
0.000000000000000000 % ==
0.100000000000000010 % ==
0.200000000000000010 % ==
0.300000000000000040 % ~= as !
0.400000000000000020 % ==
   -and-
format hex;
hd=[a.',b.']
hd =
0000000000000000 0000000000000000 % ==
3fb999999999999a 3fb999999999999a % ==
3fc999999999999a 3fc999999999999a % ==
3fd3333333333333 3fd3333333333334 % ~= !
3fd999999999999a 3fd999999999999a % ==

If you're trying to compare two floating-point numbers, be very careful about using == to do so. An alternate comparison method is to check if the two numbers you're comparing are "close enough" (as expressed by a tolerance) to one another:

% instead of a == b
% use:
areEssentiallyEqual = abs(a-b) < tol
% for some small value of tol relative to a and b
% perhaps defined using eps(a) and/or eps(b)

You can see this same sort of behavior outside MATLAB. Using pencil and paper (or a chalkboard, or a whiteboard, etc.) compute x = 1/3 to as many decimal places as you want. The number of decimal places must be finite, however. Now compute y = 3*x. In exact arithmetic, y would be exactly 1; however, since x is not exactly one third but is a rounded approximation to one third, y will not be exactly 1.

For a readable introduction to floating point arithmetic, look at Cleve's Corner article from 1996: Floating Points (PDF) (http://www.mathworks.com/company/newsletters/news_notes/pdf/Fall96Cleve.pdf)

For more rigorous and detailed information on floating point arithmetic, read the following paper: What Every Computer Scientist Should Know About Floating Point Arithmetic (http://docs.sun.com/source/806-3568/ncg_goldberg.html)

How does the backslash operator work? What does it do?

For full matrices, pseudocode describing the algorithm can be found in the MathWorks Technical Solution How does the backslash operator work when A is full? (http://www.mathworks.com/support/solutions/data/1-172BD.html?solution=1-172BD) or Operating on Sparse Matrices (http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/math/f6-8856.html).

Also for sparse matrices, you can turn on monitoring routines that show you some of the steps. Use spparms('spumoni', 1), or spparms('spumoni', 2)

How does one compute a factorial?

After MATLAB 5.3, there is a factorial function, but it is not vectorized. Why this is so we will never know. Instead, you can use the gamma function, which is vectorized. Careful, factorial(n) = gamma(n+1). If you are trying to compute a ratio of factorials, see the next question.

How can one accurately compute ratios of factorials?

If you are trying to compute "n choose k", just use the function nchoosek. Otherwise, Paul Skoczylas suggests in msgid:<bzAM5.2437$pQ4.21981@jekyl.ab.tac.net>

If I wanted to evaluate n!/(n-j)! for large values of n and/or j (but still assuming n>j), I would use the gammaln function.

   gamma(m+1)=m!
gammaln(m+1)=log(m!)

Rewrite and manipulate the equation:

   A=n!/(n-j)!
log(A)=log(n!/(n-j)!)
log(A)=log(n!)-log((n-j)!)
A=exp(log(n!)-log((n-j)!))

so,

   A=exp(gammaln(n+1)-gammaln(n-j+1))

How can I fit a circle to a set of XY data?

An elegant chunk of code to perform least-squares circle fitting was written by Bucher Izhak and has been floating around the newgroup for some time. The first reference to it that I can find is in msgid:<3A13371D.A732886D%40skm.com.au>:

function [xc,yc,R,a] = circfit(x,y)
%CIRCFIT Fits a circle in x,y plane
%
% [XC, YC, R, A] = CIRCFIT(X,Y)
% Result is center point (yc,xc) and radius R. A is an optional
% output describing the circle's equation:
%
% x^2+y^2+a(1)*x+a(2)*y+a(3)=0

% by Bucher izhak 25/oct/1991

n=length(x); xx=x.*x; yy=y.*y; xy=x.*y;
A=[sum(x) sum(y) n;sum(xy) sum(yy) sum(y);sum(xx) sum(xy) sum(x)];
B=[-sum(xx+yy) ; -sum(xx.*y+yy.*y) ; -sum(xx.*x+xy.*y)];
a=A\B;
xc = -.5*a(1);
yc = -.5*a(2);
R = sqrt((a(1)^2+a(2)^2)/4-a(3));

Tom Davis provided a more sophisticated approach that works for more cases in msgid:<3C76E5AA.350DA497@eng.usf.edu> and msgid:<3C785735.F7F192BC@eng.usf.edu>. Code included.

Why does MATLAB return an complex number for (-8)^(1/3)

In the same way there are two solutions (plus and minus) for the square root of a positive number, there are multiple solutions for roots of negative (and complex) numbers. If you express the number in magnitude*exp(i*theta) form, the cube root (for instance) takes the form (magnitude^(1/3))*exp(i*theta/3*k), for k=1:3.

-8 is 8*exp(i*pi), so the cube roots are 2*exp(i*pi/3), 2*exp(2*i*pi/3), and 2*exp(3*i*pi/3). The last one simplifies to -2.

MATLAB always returns the first solution counter-clockwise from the positive real axis. Armed with this knowledge, you can compute all or some particular root. For instance, if you want the negative real cube root, simply take the cube root of the absolute value of the number, and negate it.

For a different wording and more information, see the related [MathWorks Tech Solution http://www.mathworks.com/support/solutions/data/1-15M1N.html?solution=1-15M1N].

Finally, Joe Sababa suggests in msgid:<eeada27.1@WebX.raydaftYaTP> a method to find all the roots at once:

Find the roots of a polynomial:

P=[1 0 0 27]; 
roots(P)

An alternate method to obtain -2 as a cube root of -8 is to use the NTHROOT function:

x = nthroot(-8, 3)

x =

   -2

Can I compute the DFT of an irregularly-sampled signal?

Ken Davis writes:

The easiest way to find the spectrum of irregularly sampled data is to resample it to uniform samples. You can do this with MATLAB's interp1 function. The accuracy of your spectrum will depend on the accuracy of the interpolation. You will want to experiment with several of the interpolation methods that are available in interp1. I believe that for interpolation with a limited window (i.e. interpolating a sample value from N nearest neighbors), the Lagrange interpolation is optimal, but Lagrange is not one of the choices in interp1.

If interpolation doesn't work there are other schemes available. The Lomb-Scargle periodogram is often mentioned in relation to this question and may be more appropriate if your data has very uneven spacing (e.g. very large or very small spacings). I know that this algorithm is listed in Numerical Recipes, but I don't have a good on-line reference (with MATLAB code) to point you to.

In general, the problem is that the spacing between points determines the "importance" of a particular point. For example, if several points are very close together, then small amounts of noise on those measurements will tend to have a greater effect on inferring the slope of the function (and with it, the high frequency energy) than the same amounts of noise on measurements that are further apart.

How can I efficiently do row-wise vector-matrix multiplication?

Elaborating on the question, the for-loop implementation looks like:

for row = 1:N
output(row, :) = vector(row) * matrix(row, :);
end

In recent MATLAB versions (>= 6.5), this is actually not such a bad idea, as the accelerator will do a good job on a loop like this.

The "old-style" vectorized version of this uses repmat.

output = matrix .* repmat(vector, 1, M);

This is a fine solution, except that having to replicate vector uses memory unnecessarily, and is less cache-efficient. The accelerated single loop may run faster in some cases, due to the better cache-usage.

Finally, there is a solution using sparse. Ken Davis writes:

If A is MxN and B is Nx1 or 1xN, then A*sparse(1:N, 1:N, B) multiplies the columns of A by the elements of B. Similarly, sparse(1:M, 1:M, B)*A multiplies the rows of A by the corresponding elements of B. For division, use 1./B in place of B as the argument to sparse.

This solution requires the conversion of the full vector to a sparse format, but the actual computation will be very fast. The fastest solution depends on the sizes involved, so try them all!

Installation, Crashes, Platform-Specific Issues

MATLAB 5.3 won't run on my linux system.

First try matlab -n to see which shared libraries MATLAB can or can't find. If you get a "file not found" error instead of a list of shared libraries, you're missing `/lib/ld.so.1' or something similar. Otherwise you will see the name of each library MATLAB needs and the location of the one it found. The big one is libc5.

If you are missing `/lib/ld.so.1', you probably don't have the correct version of the linux dynamic linker. Your distribution likely offers libc5 compatibility packages.

Greg Wolodkin suggests:

I would download 1.9.11 (the tar.gz file from the above site), untar it, and run the `instldso.sh' script therein. Run it a second time using --force after you read the information displayed.

After fixing the ld.so problem, I also had to install X libraries which were compatible with libc5. www.xfree86.org has binaries for that kind of system... drop the lib files in a different directory (`/usr/X11R6/lib-compat' or something), add this to `/etc/ld.so.conf', and re-run ldconfig.

Lars Jansson shares his easy Redhat solution, using RPMs from an old version of Redhat:

% rpm -i /Path_to_RedHat_6.2_CD/RedHat/RPMS/ld.so-1.9.5-13.i386.rpm
% rpm -i /Path_to_RedHat_6.2_CD/RedHat/RPMS/libc-5.3.12-31.i386.rpm

Don Chorman has instructions for Suse 7.3, from thread msgid:<aaime6$2cen$1@msunews.cl.msu.edu>:

Before I installed MATLAB, I installed the shlibs5(old version 5) package. This package came on one of the installation CD's. I used the Yast2 control center to install the package. Under Sofware - add/remove, search the packages for shlibs to find the package) Package info:

--------------------------------------------------------------------------
Version: 2001.7.30-22, Thu Sep 20 00:13:43 2001
Required by: shlibs5
Description: Shared C libraries needed to run programs linked
with libc and libm libraries (version 5).
--------------------------------------------------------------------------

Why do I get a segfault after compiling correct MEX files under linux?

Christian Joensson answers:

I suspect you have MATLAB 5.2.1 (R11.1) or prior and that you have a libc6 (glibc2) based linux system. Either (1) upgrade to MATLAB 6 (R12) or (2) downgrade to a libc5 based linux system or (3) use the cross-compiler mentioned in The MathWorks Tech Solution (http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/matlab_external/f24626.html).

If you run a RedHat system, the solution above contains cookbook instructions for installing a libc5 cross-compiler that will happily co-exist with your regular compiler. If you run a different distribution, use the above solution as a guide, but you will need to do some hacking to get things all set up. If you can provide a detailed fix for a specific system other than the one mentioned here, please email the maintainer of this FAQ!

Why does MATLAB 6.0 crash on my Pentium 4?

If the error message you receive is "Failure Loading Desktop Class", see solution 27293 at The MathWorks: http://www.mathworks.com/support/solutions/data/1-1A2L7.html?solution=1-1A2L7

How can I make MATLAB 6.0 (R12) open without the GUI?

Start MATLAB using the command matlab -nodesktop. A related switch is -nojvm, which starts MATLAB without the Java Virtual Machine, making it take much less memory. However many of the editor and browser features will not work.

Why does MATLAB 6.0 crash under Redhat 7.0?

Greg Wolodkin writes in msgid:<94msc5$61m$1@news.mathworks.com>:

This is a well-known bug in the version of glibc (2.1.92) that Redhat chose to ship with Redhat 7.0. Any program which uses LinuxThreads is pretty much guaranteed not to work. The topic has come up in this newsgroup, though not recently.

We mention the Redhat 7 problems in the release notes. There is also a tech support SWAT (http://www.mathworks.com/support/solutions/data/1-182DV.html?solution=1-182DV) available at http://www.mathworks.com/support; search for redhat 7 and it will be the only hit.

The fix is to upgrade to glibc 2.1.94 or better. I'd recommend glibc 2.2 at this point.

A short-term work-around is to start using matlab -nojvm which makes MATLAB a single-threaded program.

Why can't I type into the command window?

Greg Wolodkin writes in msgid:<9de9hp$avr$1@news.mathworks.com>:

If you are running XFree86 4.0, try turning off your num lock key. Or upgrade to the very latest XFree86 4.0.x where I believe that bug is fixed.

As a short-term workaround you can use "matlab -nojvm" to get back to the R11 xterm interface, which doesn't have this problem.


How do I release a MATLAB license?

Follow the instructions in technical support solution document 1-15HLG (http://www.mathworks.com/support/solutions/data/1-15HLG.html?solution=1-15HLG).

Is MATLAB optimized for the Pentium IV?

MATLAB 6.5 (Release 13) does indeed contain BLAS libraries optimized for the Pentium IV, though more recent versions of ATLAS (the BLAS library included with MATLAB) will further increase performance.

If you are using Release 12 or want to try to improve performance, you can compile your own. Kevin Sheppard has been kind enough to prepare a web page with instructions for compiling your own ATLAS libraries on windows. He also provides ready-to-download DLLs for most common x86 processors. Find it at http://weber.ucsd.edu/~ksheppar/matlab/MatlabAtlas.htm.

If you are running Linux, search the newsgroup archives for references to ATLAS. It is straightforward to compile your own customized version.

Why doesn't Ctrl-C interrupt execution of my m-file?

This is likely to be a problem only under Windows, where MATLAB must poll for Ctrl-C events. If it is deep within matrix computation, it will simply not respond. If this occurs inside a loop construct, you can force MATLAB to poll more often by inserting drawnow or pause(0) into the loop. This will also update your figures and make GUIs more responsive.

Why does MATLAB 7.0 (R14) crash on startup on my AMD Sempron or AMD Turion machine?

Follow the instructions in technical support solution document 1-YNRQP (http://www.mathworks.com/support/solutions/data/1-YNRQP.html?solution=1-YNRQP) to change the BLAS_VERSION environment variable to atlas_Athlon.dll.

Toolboxes, Software Archives, Books, and Other Resources

Where can I find archives of user-contributed MATLAB software?

The MathWorks has launched a new website for user-contributed MATLAB files: http://www.mathworks.com/matlabcentral/fileexchange/ .

Where can I find a package to perform a specific task?

First, see the previous question for the first place to look.

Styled Text Toolbox: written by Doug Schwarz, this toolbox allows extremely flexible formatting of text strings, including symbols, math formulae, etc. Its TeX interpreter is much more complete than the builtin MATLAB interpreter. http://www.frontiernet.net/~dmschwarz/stextfun/index.html

MATLAB and LaTeX: Arno Linnemann has written an M-file to simplify the inclusion of MATLAB graphics into LaTeX documents, along with a nice document of tips and tricks. http://www.uni-kassel.de/~linne/matlab/WelcomeEng.html

Genetic Algorithm Optimization Toolbox: GAOT implements simulated evolution in the MATLAB environment. Written by the Meta-Heuristic Research and Applications Group at the North Carolina State University Department of Industrial Engineering: http://www.ise.ncsu.edu/mirage/GAToolBox/gaot/

What textbook would you recommend for learning MATLAB?

A popular textbook for a general audience is Mastering MATLAB 6 by Duane Hanselman and Bruce Littlefield (http://www.eece.maine.edu/mm/). Other more specialized textbooks on a variety of disciplines are listed on the MathWorks web site at http://www.mathworks.com/support/books/.

Where can I find MATLAB Style Guides or Coding Standards?

Michael Robbins started and summarized a great thread on this topic. Michael has graciously allowed me to post his PDF summary here: http://www.mit.edu/~pwb/cssm/GMPP.pdf. Or read this entire newsgroup thread: Good MATLAB programming practices (http://www.mathworks.com/matlabcentral/newsreader/view_thread/15500).

Richard Johnson has written a style guide for MATLAB. The advice is not universal, but there are many good points and suggestions. http://www.datatool.com/prod02.htm

Both of these papers can also be found in the "White Papers" section of MATLAB Central File Exchange.

Simulink

How do I insert a Simulink model into an MS Office Document?

Ikaro Silva contributed this answer:

A quick way to do this is to use a screen capture of the model. To take a screen capture under Windows, press Alt+PrintScreen to copy a bitmap of the current window to the clipboard. Then paste it into your document using Ctrl+V or RightClick->Paste.

In R12.x you can also copy the model to the clipboard from the Edit menu within Simulink.

What are best practices for modeling communications systems with Simulink?

This section is currently under construction.

Simulink for communications modeling

Miscellaneous


Can I use MATLAB to interface to an RS232 serial port?

If you are still using MATLAB 5.x, you might find something on this page:

File Exchange > Test and Measurement > Applications and Examples (http://www.mathworks.com/matlabcentral/fileexchange/loadCategory.do?objectId=120&objectType=Category)

If you are using MATLAB 6.0, the SERIAL function should help you out.

I've seen system_dependent on the newsgroup before. What does it do?

It is an undocumented, builtin function that can be used to look at things like memory allocation. Not much is known about it, which is probably good, because it is undocumented for a reason.

First, don't blame us if your computer explodes due to trying these! (they seem safe, though:) Since you asked:

system_dependent(13): prints out a summary of MATLAB memory cache 
system_dependent(13, 1): a more detailed summary
system_dependent(13, 2): a ridiculously detailed printout of the cache
system_dependent('tabcompletion',0): turns off tab completion

Why does bench run so much slower in MATLAB 6.x than in 5.x?

From the help text for bench.m:

This benchmark is intended to compare performance of one particular version of MATLAB on different machines. It does not offer direct comparisons between different versions of MATLAB. The tasks and problem sizes change from version to version.

However, Mark Brown writes:

That's not exactly true. You can save BENCH.M from the previous version and use it to measure the speed of the new version. That's what I did. Here' the results:

                       ODE   LU   Sparse    3-D   2-D
Bench5 on Matlab5 0.5 0.38 0.36 1.37 2.03
Bench5 on Matlab6 2.33 0.21 0.35 1.28 2.19
                        LU   FFT   ODE  Sparse   2-D   3-D
Bench6 on Matlab6 2.70 3.25 2.50 2.73 3.52 4.13


I had to patch the ODE functions in BENCH5 so it would run on MATLAB 6 because TMW changed syntax and it wouldn't run without error. So ignore the comparison of ODE performance. All other functions were unchanged, however.

What is vectorization?

Vectorization is the process of writing code for MATLAB that uses matrix operations or other fast builtin functions instead of using for loops. The benefits of doing this are usually sizeable. The reason for this is that MATLAB is an interpreted language. Function calls have very high overhead, and indexing operations (inherent in a loop operation) are not particularly fast.

See also: #What is Acklamization?

What is Acklamization?

As contributed by Gautam Sethi:

Acklamize (v) 
To take any MATLAB code and modify it for the explicit purpose of refining and perfecting. The refinements may be aesthetic in one or more of the following ways: memory use, processing speed or sheer elegance in its written form. Also see Acklamizer(n).
Acklamizer (n) 
An individual who indulges in the process of acklamization. See Acklamize (v).

Acklamization is named after Peter Acklam, a regular participant in comp.soft-sys.matlab and an expert in what is now termed acklamization. Take a look at his web site of MATLAB array manipulation tips and tricks (http://home.online.no/~pjacklam/matlab/doc/mtt/index.html).

See also: #What is vectorization?

Why does MATLAB needlessly access the floppy drive?

This annoying behavior sometimes manifests itself when using the DOS, UNIX, or ! commands to execute external programs. It is likely due to the virus checking software installed on your computer. You can get rid of this behavior by going to the properties of your virus detection software, and unchecking the "Scan floppies on access" option or something like that. The details may depend on which anti-virus software you're using.

How do I run MATLAB in batch mode?

Steve Lord contributed this answer:

On the PC, you can use the /r flag to start your m-file immediately upon starting MATLAB. Using this in combination with the Windows Task Manager, you can set a MATLAB job to run when you want it to run, even if you are not at the computer. Please note that you will need to exit MATLAB at the end of the m-file. Alternately, if you only want a single file to run, you can name it startup.m and place it in your MATLAB directory.

For UNIX, you can use the AT or CRON commands to execute a script which runs MATLAB. In the script, use this general syntax:

matlab < MyMFile

If you want to record output, either use the SAVE command inside your m-file or redirect the output of the MATLAB session to a file using this syntax:

matlab < MyMFile > MyOutputFile

This syntax only works for scripts. If you need to run a function, create a wrapper script that calls the function.

Comments