Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

[FAQ] MATLAB FAQ

45 views
Skip to first unread message

Peter Boettcher

unread,
Sep 17, 2002, 4:03:34 AM9/17/02
to
MATLAB FAQ

Frequently asked questions in comp.soft-sys.matlab


Last modified: <Wed Jul 24 17:18:58 2002 by pwb>

Recent Changes:

(+) New Question
(%) Modified Question
* (+) Q3.9: How do I dynamically generate a filename for SAVE?
_________________________________________________________________

Table of Contents

* Introduction
* 1 Introduction, Policy, Credits
+ Q1.1: What is MATLAB?
+ Q1.2: What is this newsgroup about?
+ Q1.3: Where can I find an archive of comp.soft-sys.matlab?
+ Q1.4: What other software packages exist to do similar work?
+ Q1.5: What is the FAQ editorial policy?
+ Q1.6: Who maintains this FAQ?
+ Q1.7: Contributors
* 2 Basics
+ Q2.1: Why does MATLAB only calculate to 4 significant digits?
+ Q2.2: Why does the transpose operator take the complex
conjugate?
+ Q2.3: How can I set all NaN's to 0?
+ Q2.4: How can I make MATLAB use the full window width for
displaying matrices?
+ Q2.5: How do I comment out a large block of code?
+ Q2.6: How do I save default settings across sessions?
+ Q2.7: How can I find local maxima in a vector array?
+ Q2.8: Why is 6*i not complex in my program?
* 3 Programming
+ Q3.1: Can I read a text file with a certain format?
+ Q3.2: Why are global variables bad?
+ Q3.3: What about this logical array business?
+ Q3.4: Huge memory waste using array of structs?
+ Q3.5: Why is my MEX file crashing?
+ Q3.6: How can I create variables A1, A2,...,A10 in a loop?
+ Q3.7: Do boolean operators short-circuit?
+ Q3.8: How do I fix "Out of Memory" problems?
+ Q3.9: How do I dynamically generate a filename for SAVE?
* 4 Graphics
+ Q4.1: How do I adjust the fontsize of a ticklabel?
+ Q4.2: Can I create a pi/sigma/superscript in my ticklabels?
+ Q4.3: Can I open multiple files using uigetfile?
+ Q4.4: I want to use a scrollbar to scroll my edit
boxes/buttons
+ Q4.5: How can I rotate ticklabels?
+ Q4.6: How can I display data in a grid like Excel?
+ Q4.7: How can I write a title or text with multiple lines?
+ Q4.8: How can I use a common color scale among several
images?
+ Q4.9: How can I set default handle graphics properties?
+ Q4.10: How can I modify the default background color used for
histograms?
+ Q4.11: How can I draw more than two lines with plotyy?
+ Q4.12: Is there a command available for plotting an arrow on
a graph?
+ Q4.13: Why does movie(M,1) display the movie M twice?
+ Q4.14: How can I set the focus in my GUI?
* 5 Math/Algorithms
+ Q5.1: Why is 0.3-0.2-0.1 not equal to zero (or similar)?
+ Q5.2: How does the backslash operator work? What does it do?
+ Q5.3: How does one compute a factorial?
+ Q5.4: How can one accurately compute ratios of factorials?
+ Q5.5: How can I fit a circle to a set of XY data?
+ Q5.6: Why does MATLAB return an complex number for (-8)^(1/3)
* 6 Installation, Crashes, Platform-Specific Issues
+ Q6.1: MATLAB 5.3 won't run on my linux system.
+ Q6.2: Why do I get a segfault after compiling correct MEX
files under linux?
+ Q6.3: Why does MATLAB 6.0 crash on my Pentium 4?
+ Q6.4: How can I make MATLAB 6.0 (R12) open without the GUI?
+ Q6.5: Why does MATLAB 6.0 crash under Redhat 7.0?
+ Q6.6: Why can't I type into the command window?
+ Q6.7: What happened to MATLAB for the Macintosh?
+ Q6.8: How do I release a MATLAB license?
+ Q6.9: Is MATLAB optimized for the Pentium IV?
+ Q6.10: Why doesn't Ctrl-C interrupt execution of my m-file?
* 7 Toolboxes, Software Archives, Books, and Other Resources
+ Q7.1: Where can I find archives of MATLAB software?
+ Q7.2: Where can I find a package to perform a specific task?
+ Q7.3: What textbook would you recommend for learning Matlab?
+ Q7.4: Where can I find MATLAB Style Guides or Coding
Standards?
* 8 Simulink
+ Q8.1: How do I insert a Simulink model into an MS Office
Document?
* 9 Miscellaneous
+ Q9.1: Why does MATLAB 6.0 (R12) take so much memory?
+ Q9.2: Can I use MATLAB to interface to an RS232 serial port?
+ Q9.3: I've seen system_dependent on the newsgroup before.
What does it do?
+ Q9.4: Why does bench run so much slower in MATLAB 6.x than in
5.x?
+ Q9.5: What is vectorization?
+ Q9.6: What is Acklamization?
+ Q9.7: Why does MATLAB needlessly access the floppy drive?
+ Q9.8: How do I run MATLAB in batch mode?
_________________________________________________________________

MATLAB FAQ
**********

Introduction
************

This is a list of frequently asked questions (with answers)
pertaining to MATLAB. The current version of MATLAB at the time this
document was written is 6.1 (R12).

This FAQ is freely redistributable. I take no liability for the
correctness and safety of any procedures or advice given here. This FAQ
is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. Further, any opinions contained
herein are my own and not necessarily shared by my employer.

I do require that if you redistribute this document, you do so in
unmodified form. This simply helps ensure it will remain up-to-date.
If you are interested in a different formatting, check with me first, as
it may be easy to produce from the texinfo source.

This FAQ is independent of and does not represent The MathWorks in
any way. The MathWorks does not officially sponsor, approve, or endorse
this FAQ or its content.

The official and most recent hypertext version of this document can
be found at <http://www.mit.edu/~pwb/cssm/>.

1 Introduction, Policy, Credits
*******************************

Q1.1: What is MATLAB?
=====================

MATLAB is a commercial software package written by The Mathworks
(http://www.mathworks.com). Quoting from their web page:

Numeric computation, technical graphics and visualization, and an
intuitive programming language for applications in engineering and
science

MATLAB is a complete environment for high-level programming, as well
as interactive data analysis. MATLAB excels at numerical computations,
especially when dealing with vectors or matrices of data. Symbolic math
is available through an add-on toolbox that uses a Maple kernel.

There are too many toolbox add-ons to describe here. Poke around the
web site if you have some interest.

Questions about the name "MATLAB" often arise. MATLAB stands for
"MATrix LABoratory". See
<http://www.mathworks.com/access/helpdesk/help/techdoc/learn_matlab/ch1intro.shtml>
for an overiew of MATLAB.

Q1.2: What is this newsgroup about?
===================================

The newsgroup `comp.soft-sys.matlab' (sometimes abbreviated cssm) is
a forum for discussing issues related to the use of MATLAB. It
occasionally includes questions related to similar software packages
like Octave. Any topic related to MATLAB is appropriate. Additionally,
there will be occasional discussions regarding related math topics in a
more abstract form.

The original charter for the group, created in early 1993, can be
found at
<http://www.landfield.com/usenet/news.announce.newgroups/comp/comp.soft-sys.matlab>.

Before posting, please skim through this document to see if your
question has already been answered. If it is has not, there may be
information here that may help you better understand the issue and
phrase your question.

Q1.3: Where can I find an archive of comp.soft-sys.matlab?
==========================================================

Try the standard newsgroup archive at <http://groups.google.com>.

Many people are also now using the web-based newsreader provided by
the MathWorks at their website, which contains archives back to
mid-2000. It provides full posting capability. See
<http://www.mathworks.com/matlabcentral/>.

There is also a complete, searchable archive of cssm at
<http://mathforum.org/epigone/comp.soft-sys.matlab/>. It probably
contains the earliest articles of these services.

Q1.4: What other software packages exist to do similar work?
============================================================

GNU Octave is a freely availabe software package with a language
"mostly compatible with MATLAB": <http://www.octave.org>.

Scilab "is a scientific software package for numerical computations
in a user-friendly environment". It is fully open source and has a
parallel version. <http://www-rocq.inria.fr/scilab/>.

IDL (Interactive Data Language) is a commericial software package
with applications similar to MATLAB. It is very well suited to image
processing and 3D visualization. IDL is produced by Research Systems
Inc., <http://www.rsinc.com>.

O-Matrix is a commercial MATLAB-like program. In fact it has a
MATLAB compatibility mode, which the authors claim can execute native
MATLAB code 5-10 times faster than MATLAB. Readers who have used this
package are encouraged to send me a more detailed explanation.
<http://www.omatrix.com>

LyME runs a reasonable subset of MATLAB code on the Palm platform.
Available for free at <http://www.calerga.com>. Thanks to Martin Cohen
for this info.

Q1.5: What is the FAQ editorial policy?
=======================================

This FAQ is actively maintained and should be up to date. All
submissions are welcome; please email submissions to the maintainer:
<boet...@ll.mit.edu>. Submissions could be new questions (preferably
with answers), fixes such as dead links or typos, extra information to
elaborate on an answer, or a replacement answer.

Questions and answers will be edited, and will be attributed.
Anything appearing without attribution was written by the FAQ
maintainer or by someone listed in the contributor section, unless it
is explicitly indicated as unknown or anonymous source. Where answers
are quoted from Usenet news articles, they will always be attributed.

Q1.6: Who maintains this FAQ?
=============================

This FAQ was created by Peter Boettcher <boet...@ll.mit.edu> in
early 2001. He is also the current maintainer.

Q1.7: Contributors
==================

Thanks to Denis Gilbert for a substantial set of questions and
answers, as well as feedback on existing answers. Many others have
contributed suggestions and answers, which are individually attributed.

2 Basics
********

Q2.1: 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.

Q2.2: 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

Q2.3: How can I set all NaN's to 0?
===================================

NaN's are tricky. `NaN==NaN' is false, so you can't say `x(x==NaN)
= 0;' Instead, use the function `isnan', as in: `x(isnan(x)) = 0;'

Q2.4: How can I make MATLAB use the full window width for displaying matrices?
==============================================================================

Bob Gilmore <bgil...@mathworks.com> 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.

Q2.5: How do I comment out a large block of code?
=================================================

The built-in editor in MATLAB 6.0 now has a block-comment feature.
Or you can use matlab-mode
(http://www.mathworks.com/support/ftp/emacs_add_ons.shtml) for Emacs,
which supports this as well.

If you are using an 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.

Q2.6: 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.

Q2.7: 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 );

Q2.8: Why is 6*i not complex in my program?
===========================================

You might have overwritten the variable i with a number earlier in
your program (or session, for that matter). You can reset i using
i=sqrt(-1), or "clear i", or you can use j, or you can use the function
"complex".

3 Programming
*************

Q3.1: 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.

Q3.2: Why are global variables bad?
===================================

us <u...@neurol.unizh.ch> writes in
<http://groups.google.com/groups?selm=90mer5$1u8$1...@nnrp1.deja.com>
(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 ok (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 book-keeping if(f) 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 ML 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.

Q3.3: 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.

Q3.4: 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 <cr...@ph.tn.tudelft.nl> 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.

Q3.5: Why is my MEX file crashing?
==================================

Memory errors are one likely reason. Greg Wolodkin
<gr...@fess.mathworks.com> 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.

Q3.6: 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!

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. Repeat: don't do this
unless you have a very good reason (such as someone gives you a MAT
file with 2000 variables named A1428, for example).

Q3.7: 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.

In MATLAB, boolean operators are only short-circuit evaluated inside
the conditions of IF and WHILE statements. In all other contexts, all
parts of the conditional are evaluated. For an interesting discussion
on this topic, see

<http://groups.google.com/groups?selm=twhf7jk...@frenchslinux.dhcp>

Q3.8: 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>

Q3.9: 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.

4 Graphics
**********

Q4.1: 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.

Q4.2: 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. The following MathWorks
solutions may give you some guidance:

<http://www.mathworks.com/support/solutions/data/27450.shtml>

and

<http://www.mathworks.com/support/solutions/data/5375.shtml>

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.servtech.com/~schwarz/stextfun/index.html>

Q4.3: Can I open multiple files using uigetfile?
================================================

No, but there is file called `uigetfiles.dll' on The MathWorks web
site that will allow you to do this, at least on a Windows platform. It
can be found on this page:
<http://www.mathworks.com/matlabcentral/fileexchange/Files.jsp?type=category&id=&fileId=331>

Q4.4: 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 <gha...@s2.chalmers.se> 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

Q4.5: How can I rotate ticklabels?
==================================

You can't do that directly. Use the following Mathworks solutions to
place the labels manually as text objects (this is a hack):

<http://www.mathworks.com/support/solutions/data/5375.shtml>

Q4.6: 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 in MATLAB 6. Type
`openvar(my_var)' at the command prompt, or double click on the
variable in the workspace browser. This editor is limited to 2-D
matrices of less than 10000 elements.

If you are working on a PC, an ActiveX object is the way to go. Try
searching the archive for "activex" and "grid". Michael Robbins has
posted a number of articles on this topic, so you might try adding his
name to the search. Try a search like this:

<http://groups.google.com/advanced_group_search?as_ugroup=comp.soft-sys.matlab&as_uauthors=robbins&as_q=activex%20grid>

Q4.7: 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'})

Q4.8: 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.

Q4.9: 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

Q4.10: 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');

Q4.11: 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')

Q4.12: 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>

Q4.13: 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.

Q4.14: 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.

5 Math/Algorithms
*****************

Q5.1: Why is 0.3-0.2-0.1 not equal to zero (or similar)?
========================================================

(The above example returns -2.7756e-17.) Jason Bowman
<jbow...@hotmail.com> 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.

us <u...@neurol.unizh.ch> elaborates:

Watch Jason's response unfolding:
a=[0 0.1 0.2 0.3 0.4];
b=[0:.1:.4];

sprintf('%20.18f\n',a)
ans =
0.000000000000000000
0.100000000000000010
0.200000000000000010
0.299999999999999990
0.400000000000000020

sprintf('%20.18f\n',b)
ans =
0.000000000000000000
0.100000000000000010
0.200000000000000010
0.300000000000000040
0.400000000000000020

For more detail then you ever will want on floating point arithmetic,
skim the following paper: "What Every Computer Scientist Should Know
About Floating Point Arithmetic":
<http://www.validlab.com/goldberg/paper.ps>

Also take a look at the wonderful Cleve's Corner article from 1996.
It is much more accessible than the previous link.
<http://www.mathworks.com/company/newsletter/pdf/Fall96Cleve.pdf>

Q5.2: How does the backslash operator work? What does it do?
=============================================================

For full matrices, pseudocode describing the algorithm can be found
here:

<http://www.mathworks.com/support/solutions/data/22317.shtml>

For sparse matrices, the URL is:
<http://www.mathworks.com/support/solutions/data/21798.shtml>

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)'

Q5.3: 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.

Q5.4: 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 <pa...@cfertech.com> suggests in
<http://groups.google.com/groups?selm=bzAM5.2437$pQ4....@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))

Q5.5: 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
<http://groups.google.com/groups?selm=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
<http://groups.google.com/groups?selm=3C76E5AA...@eng.usf.edu> and
<http://groups.google.com/groups?selm=3C785735...@eng.usf.edu>.
Code included.

Q5.6: 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
<http://www.mathworks.com/support/solutions/data/2998.shtml>.

Finally, Joe Sababa <joes...@yahoo.com> suggests in
<http://groups.google.com/groups?selm=eead...@WebX.raydaftYaTP> a
method to find all the roots at once:

Find the roots of a polynomial:
P=[1 0 0 27];
roots(P)

6 Installation, Crashes, Platform-Specific Issues
*************************************************

Q6.1: 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 <gr...@fess.mathworks.com> 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 <l...@s2.chalmers.se> 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 <chor...@bounce-msu.edu> has instructions for Suse 7.3,
from thread
<http://groups.google.com/groups?selm=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).
--------------------------------------------------------------------------

Q6.2: Why do I get a segfault after compiling correct MEX files under linux?
============================================================================

Christian Joensson <c.christia...@telia.com> 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 at
<http://www.mathworks.com/support/solutions/data/11129.shtml>

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!

Q6.3: 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/27293.shtml>

Q6.4: 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.

Q6.5: Why does MATLAB 6.0 crash under Redhat 7.0?
=================================================

Greg Wolodkin <gr...@fess.mathworks.com> writes in
<http://groups.google.com/groups?selm=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 available at
<http://www.mathworks.com/support'; search for `redhat 7> and it
will be the only hit.

<http://www.mathworks.com/support/solutions/data/26841.shtml>

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.

Q6.6: Why can't I type into the command window?
===============================================

Greg Wolodkin <gr...@fess.mathworks.com> writes in
<http://groups.google.com/groups?selm=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.

Q6.7: What happened to MATLAB for the Macintosh?
================================================

This is a very sore point with many cssm readers! MATLAB Development
for the Macintosh ceased some time ago. The last supported release is
MATLAB 5.2.1. Matt Jones <jone...@physiology.wisc.edu> reports that
although it is old, it still works well on all MAC operating systems
since 8.6, including classic mode in OSX, with little or no performance
hit.

News Flash!: Cleve Moler just announced via post in CSSM that MATLAB
was returning to the Macintosh. He predicts availability "later this
year". Read the thread here (it's only one post as I write this, but I
predict it will be sizeable):
<http://groups.google.com/groups?selm=ab6md9$s8b$1...@madmax.mathworks.com>

Q6.8: How do I release a MATLAB license?
========================================

The MathWorks has prepared an answer to this question at:

<http://www.mathworks.com/support/solutions/data/976.shtml>

Q6.9: Is MATLAB optimized for the Pentium IV?
=============================================

No, but I have not yet heard a good explanation for this. 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 (but not yet for the Pentium IV). 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.

If anyone has any idea why The MathWorks has not released these yet,
please let me know. I cannot come up with a logical guess.

Q6.10: 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.

7 Toolboxes, Software Archives, Books, and Other Resources
**********************************************************

Q7.1: Where can I find archives of MATLAB software?
===================================================

The Mathworks has launched a new website for user-contributed MATLAB
files: <http://www.matlabcentral.com/> This URL replaces the old FTP
site.

Another nice archive can be found at Mathtools.net, at
<http://www.mathtools.net/MATLAB/index.html>

Q7.2: Where can I find a package to perform a specific task?
============================================================

_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.servtech.com/~schwarz/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>

_Connectaxes_: Wolfgang Hammer has written a function that is used
in conjunction with zoom. It allows zoom in one axes to control other
axes. <http://www.lem.ee.ethz.ch/plecs/GOODIES/e_goodies_misc.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.ie.ncsu.edu/mirage/>

Q7.3: 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/>.

Q7.4: Where can I find MATLAB Style Guides or Coding Standards?
===============================================================

Michael Robbins <michael...@us.cibc.com> 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
the entire thread (all 62 message!) starting with:
<http://groups.google.com/groups?selm=14228c8c...@usw-ex0104-026.remarq.com>.

Richard Johnson has recently 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>

8 Simulink
**********

Sorry, I don't use simulink. Submissions for this section are
gratefully accepted.

Q8.1: How do I insert a Simulink model into an MS Office Document?
===================================================================

Ikaro Silva <isi...@mathworks.com> 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.

9 Miscellaneous
***************

Q9.1: Why does MATLAB 6.0 (R12) take so much memory?
====================================================

Jason Bowman <jbow...@hotmail.com> writes:

Sorry I can't be of more help. I think you're stuck with the
beast that R12 is since `-nojvm' and `-nodesktop' are only showing
marginal improvements. Fortunately, the `-nojvm' option in Windows
does bring R12 memory down near where 5.3 was, but the editor gets
screwed up if I remember correctly.

Q9.2: 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:
<http://www.mathworks.com/matlabcentral/fileexchange/Category.jsp?type=category&id=34>

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

Q9.3: 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

Q9.4: 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 <mark_w...@mail.northgrum.com> 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
Matlab6 because TMW changed syntax and it wouldn't run without
error. So ignore the comparison of ODE performance. All other
functions were unchanged, however.

Q9.5: 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: Q9.6: What is Acklamization?

Q9.6: What is Acklamization?
============================

As contributed by Gautam Sethi <gau...@nospam.are.berkeley.edu>:

*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" at
<http://home.online.no/~pjacklam/matlab/doc/mtt/index.html>.

See also: Q9.5: What is vectorization?

Q9.7: 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.

Q9.8: How do I run MATLAB in batch mode?
========================================

Steve Lord <sl...@mathworks.com> 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.

0 new messages