## Basics[edit] ## 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. [edit] ## 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 [edit] ## 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 % Find NaN values in two different ways [edit] ## 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. [edit] ## How do I comment out a large block of code?Starting in MATLAB 7 (R14), the syntax is:
%{
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
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. [edit] ## 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. [edit] ## 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) [edit] ## 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) - Clear your redefinition of i
clear i - Use j instead of i
y = 6*j; - Use the COMPLEX function
y = complex(0, 6); [edit] ## 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'. [edit] ## 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. [edit] ## Programming[edit] ## 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. [edit] ## Why are global variables bad?Urs (us) Schwarz writes in [1] ( 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. 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. [edit] ## 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. [edit] ## 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. [edit] ## 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 On Unix with csh or tcsh: % setenv MATLAB_MEM_MGR debug 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. [edit] ## 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 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 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'}; 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 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) 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 is now a struct array with 2000 fields, S.A1 through S.A2000. % If the "index" of the variable you want to access is stored in a variable: [edit] ## 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 ( 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. [edit] ## 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 [edit] ## How do I dynamically generate a filename for SAVE?You're probably trying fname = 'foobag'; To do this correctly, you need to use the "functional" form of save: fname = 'foobar'; In fact, it is true in general that the following two lines are equivalent: 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. [edit] ## 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.
[edit] ## 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. [edit] ## 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 ( 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 jpgfilename = strcat('image', num2str(k), '.txt'); textfilename = ['file' num2str(k) '.txt']; 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'); [edit] ## 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". - ODE solvers like ODE45 and integration functions like QUAD or QUADL (
*http://www.mathworks.com/support/solutions/data/1-1AIJF.html?solution=1-1AIJF*) - Optimization functions in toolbox/matlab/funfun and toolbox/optim (FMINCON, FSOLVE, FZERO, LSQCURVEFIT, etc.) (
*http://www.mathworks.com/support/solutions/data/1-19HM6.html?solution=1-19HM6*) - Genetic Algorithm and Direct Search Toolbox functions (GA, PATTERNSEARCH) (
*http://www.mathworks.com/support/solutions/data/1-1BZ6V.html?solution=1-1BZ6V*)
This information has also been incorporated into the documentation in recent versions of MATLAB and the toolboxes: - MATLAB (
*http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/math/f2-941087.html*) - Optimization Toolbox (
*http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/f67947.html*) - GA function, Genetic Algorithm and Direct Search Toolbox (
*http://www.mathworks.com/access/helpdesk/help/toolbox/gads/index.html?/access/helpdesk/help/toolbox/gads/bqlex3b-1.html*) - PATTERNSEARCH function, Genetic Algorithm and Direct Search Toolbox (
*http://www.mathworks.com/access/helpdesk/help/toolbox/gads/index.html?/access/helpdesk/help/toolbox/gads/f12810.html*)
[edit] ## 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 ( [edit] ## 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:
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:
[edit] ## Graphics[edit] ## 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. [edit] ## 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 [edit] ## 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 ( [edit] ## I want to use a scrollbar to scroll my edit boxes/buttonsSorry, 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 % find handles of all the controls % exclude the handles of the 2 pushbuttons and the figure itself % loop over the remaining handles and change their positions [edit] ## 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 ( [edit] ## 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. [edit] ## 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'}) [edit] ## 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. [edit] ## 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); Similarly, you can use these statements for axes objects: set(0,'DefaultAxesLineWidth', 2); 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
[edit] ## 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); [edit] ## 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 additional line against the left y-axis [edit] ## 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 [edit] ## 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. [edit] ## 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. [edit] ## 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),'+-'); [edit] ## Math/Algorithms[edit] ## 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]; as=sprintf('%20.18f\n',a) bs=sprintf('%20.18f\n',b) -and- 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 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) ( For more rigorous and detailed information on floating point arithmetic, read the following paper: What Every Computer Scientist Should Know About Floating Point Arithmetic ( [edit] ## 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? ( 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) [edit] ## 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. [edit] ## 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! Rewrite and manipulate the equation: A=n!/(n-j)! so, A=exp(gammaln(n+1)-gammaln(n-j+1)) [edit] ## 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) 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. [edit] ## 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]; An alternate method to obtain -2 as a cube root of -8 is to use the NTHROOT function: x = nthroot(-8, 3) x = -2 [edit] ## 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. [edit] ## How can I efficiently do row-wise vector-matrix multiplication?Elaborating on the question, the for-loop implementation looks like: for row = 1:N 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! [edit] ## Installation, Crashes, Platform-Specific Issues[edit] ## 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 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: -------------------------------------------------------------------------- [edit] ## 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 ( 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! [edit] ## 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 [edit] ## 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. [edit] ## 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 ( 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. [edit] ## 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.
[edit] ## How do I release a MATLAB license?Follow the instructions in technical support solution document 1-15HLG ( [edit] ## 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. [edit] ## 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. [edit] ## 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 ( [edit] ## Toolboxes, Software Archives, Books, and Other Resources[edit] ## 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/ . [edit] ## 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/ [edit] ## What textbook would you recommend for learning MATLAB?A popular textbook for a general audience is [edit] ## 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 ( 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. [edit] ## Simulink[edit] ## 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. [edit] ## What are best practices for modeling communications systems with Simulink?This section is currently under construction. Simulink for communications modeling [edit] ## Miscellaneous
[edit] ## 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 ( If you are using MATLAB 6.0, the SERIAL function should help you out. [edit] ## 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 [edit] ## 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 LU FFT ODE Sparse 2-D 3-D
[edit] ## 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? [edit] ## 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 ( See also: #What is vectorization? [edit] ## 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. [edit] ## 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. |