MATLAB Programming/Print Version
This is the print version of MATLAB Programming You won't see this message or any elements not part of the book's content when you print or preview this page. 
Chapter 1: A Tutorial Introduction
Chapter 2: Basic MATLAB Concepts
The Current Directory and Defined Path
It is necessary to declare a current directory before saving a file, loading a file, or running an Mfile. By default, unless you edit the MATLAB shortcut, the current directory will be .../MATLAB/work. After you start MATLAB, change the current directory by either using the toolbar at the lefthand side of the screen, or entering the path in the bar at the top.
The current directory is the directory MATLAB will look in first for a function you try to call. Therefore if you have multiple folders and each of them has an Mfile of the same name, there will not be a discrepancy if you set the current directory beforehand. The current directory is also the directory in which MATLAB will first look for a data file.
If you still want to call a function but it is not part of the current directory, you must define it using MATLAB's 'set path' utility. To access this utility, follow the path:
file > set path... > add folder...
You could also go to "add folder with subfolders...", if you're adding an entire group, as you would if you were installing a toolbox. Then look for and select the folder you want. If you forget to do this and attempt to access a file that is not part of your defined path list, you will get an 'undefined function' error.
Saving Files
There are many ways to save to files in MATLAB.
 save  saves data to files, *.mat by default
 uisave  includes user interface
 hgsave  saves figures to files, *.fig by default
 diary [filename]  saves all the text input in the command window to a text file.
All of them use the syntax:
save filename.ext
or similar for the other functions. The files are saved in your current directory, as seen on the top of the window. By default the current directory is .../MATLAB/work.
Loading Files
Likewise, there are many ways to load files into the workspace. One way is to use the "file" menu. To open a .m file click "open", whereas to import data from a data file select "import data..." and follow the wizard's instructions.
An alternative way to load a saved .mat file (within a function, for example) is to type:
>> load filename.ext
The file must be in a recognized directory (usually your current directory, but at least one for which the path has been set).
The data in the .mat file is stored with the same name as the variable originally had when it was saved. To get the name of this and all other environment variables, type "who".
To open an .m file, you can use file > open, or type
>>open filename.ext
File Naming Constraints
You can name files whatever you want (usually simpler is better though), with a few exceptions:
 MATLAB for Windows retains the file naming constraints set by DOS. The following characters cannot be used in filenames:
" / : * < >  ?
 You're not allowed to use the name of a reserved word as the name of a file. For example, while.m is not a valid file name because while is one of MATLAB's reserved words.
 When you declare an mfile function, the mfile must be the same name as the function or MATLAB will not be able to run it. For example, if you declare a function called 'factorial':
function Y = factorial(X)
 You must save it as "factorial.m" in order to use it. MATLAB will name it for you if you save it after typing the function declaration, but if you change the name of the function you must change the name of the file manually, and vice versa.
Introduction
MATLAB is interesting in that it is dynamically compiled. In other words, when you're using it, you won't run all your code through a compiler, generate an executable, and then run the executable file to obtain a result. Instead, MATLAB simply goes line by line and performs the calculations without the need for an executable.
Partly because of this, it is possible to do calculations one line at a time at the command line using the same syntax as would be used in a file. It's even possible to write loops and branches at the command line if you want to. Of course this would often lead to a lot of wasted efforts, so doing anything beyond very simple calculations, testing to see if a certain function, syntax, etc. works, or calling a function you put into an .m file should be done within an .m file.
Calculator
MATLAB, among other things, can perform the functions of a simple calculator from the command line. Let us try to solve a simple problem: Sam's car's odometer reading was 3215 when he last filled the fuel tank. Yesterday he checked his odometer and it read 3503. He filled the tank and noticed that it took 10 gallons to do that. If his car's gas tank holds 15.4 gallons, how long can he drive before he is going to run out of gas, assuming the gas mileage is the same as before?
First let us compute the distance Sam's car has travelled in between the two gas fillings
>> 35033215 ans = 288
Gas mileage of Sam's car is
>> 288/10 ans = 28.8
With this, he can drive
>> 28.8 * 15.4 ans = 443.5200
443.52 miles before he runs out of gas.
Let us do the same example, now by creating named variables
>> distance = 35033215 distance = 288 >> mileage = distance/10 mileage = 28.8000 >> projected_distance = mileage * 15.4 projected_distance = 443.5200
To prevent the result from printing out in the command window, use a semicolon after the statement. The result will be stored in memory. You can then access the variable by calling its name. Example:
>>projected_distance = mileage * 15.4; >> >>projected_distance projected_distance = 443.5200
Using the command line to call functions
The command line can be used to call any function that's in a defined path. To call a function, the following general syntax is used:
>> [Output1, Output2, ..] = functionname(input1, input2,..)
MATLAB will look for a file called functionname.m and will execute all of the code inside it until it either encounters an error or finishes the file. In the former case, it produces a noise and displays an error message in red. In the latter case, MATLAB will relinquish control to you, which you can see when the >> symbol is visible on the bottom of the workspace and the text next to "start" button on the bottomleft of the screen says "ready".
Use this in order to call homemade functions as well as those built into MATLAB. MATLAB has a large array of functions, and the help file as well as this wikibook are good places to look for help on what you need to provide as inputs and what you will get back.
Be careful; the syntax for functions and for indexing arrays is the same. To avoid confusion, just make sure you don't name a variable the same as any function. To ensure this, type the name of the variable you want to define in the command prompt. If it tells you:
Error using ==> (functionname) Not enough input arguments.
then you'll have a conflict with an existing function. If it tells you:
??? Undefined function or variable '(functionname)'
you'll be OK.
External Resources
MATLAB File I/O: from the Command Line
Generic Import
importdata examines the extension and loads the data depending on the extension.
uiimport opens a window to examine data.
*.mat files
The quickest means of saving and retrieving data is through the binary .mat file format MATLAB provides. This is the native format for MATLAB.
 Note: This author has had some problems with certain classes not being saved correctly when saving data using version 7 for use in version 6. Most data items will work just fine. Of particular interest was an issue with StateSpace objects that were saved using version 7 to a version 6 compatible file. When the file was opend in MATLAB version 6+ the StateSpace objects did not load.Spradlig (talk) 04:52, 31 March 2008 (UTC).
Saving Data
The save command is used to save workspace data to a file.
 Save all workspace data to the file mySave.mat in the current directory.
>> save('mySave.mat') >> save(fullfile(pwd, 'mySave.mat'))
 Save just the variables myData1 and myData2 to mySave.mat.
>> save('mySave.mat', 'myData1', 'myData2')
 Save all myData variables to mySave.mat.
>> save('mySave.mat', 'myData*')
 Save all myData variables to a mySave.mat file compatible with version 6 of MATLAB.
>> save('mySave.mat', 'myData*', 'v6')
 Save all myData variables to an ASCII file.
>> save('mySave.mat', 'myData*', 'ASCII')
 Append new variables to the data file.
>> save('mySave.mat', 'newData*', 'append')
Loading Data
The load command is used to load data from a file into the current workspace.
 Load all variables from the file mySave.mat into the current workspace.
>> load('mySave.mat') >> load(fullfile(pwd, 'mySave.mat'))
 Load just the variables myData1 and myData2.
>> load('mySave.mat', 'myData1', 'myData2')
 Load all myData variables.
>> load('mySave.mat', 'myData*')
 Get a cell array of variables in saved file.
>> whos('file', 'mySave.mat')
Excel Spreadsheets I/O
Since analyzing data is one of the more common motivations for using input output I will start with reading and writing from a spreadsheet. I cover the command line first since it is often necessary to import the data while an mfunction is being evaluated.
Reading Excel Spreadsheets
MATLAB makes it easy to read from an Excel spreadsheet. It has the built in command "xlsread". To use the xlsread function use the syntax:
>>g=xlsread('filename');
This line of code reads filename.xls (from the current directory) and places it in an identical array inside MATLAB called g. You can then manipulate the array g any way you want. Make sure that the file you choose is in the same directory were you save your Mfiles (usually the work directory) otherwise you get an error. You can specify the path to a file but, this can get messy.
Writing Excel Spreadsheets
To write data to an .xls the procedure is very similar. The xlswrite command below creates a spreadsheet called filename.xls in the current directory from the variable g:
>> xlswrite('filename',g);
NOTE: if you are using MATLAB 6.5 there is no "xlswrite" command (that I'm aware of). There are several ways to write to a file. The simplest way I have found is
fid=fopen('newFile.xls', 'w'); fprintf(fid,'%6.3f %6.3f %10.3f\n', g); fclose(fid);
You can substitute newFile.xls with .txt. Also, there might be some issues with formatting in Excel. The formatting issues can usually be handled inside Excel but if they can't you might have to play around with the fopen command parameters. This is pretty similar (if not the same) way you would write to a file in C.
Text files I/O
Reading Text Files
If a file is not an excel spreadsheet, it can still be read using "load" function:
>> load newfile.txt
This works only if the text is entirely numerical, without special formatting. Otherwise you get an 'unrecognized character' error.
The easiest way to write to a nonexcel file, or using MATLAB 6.5 or less, is to use the same code as that for writing excel files but change the extension. Usually there are no formatting difficulties with plain text files.
For reading more general text files, MATLAB does not have a function to do it easily (unless you have excel), but you can read very general text files (with different delimiters for both cells and text within cells) using the "textread.m" function in the MATLAB file exchange (do a google search to find it). You can also try to use fscanf if the formatting is consistent enough (i.e. consistent numbers of spaces, no mixing of strings and numbers in columns, and so on).
MATLAB File I/O: from the Graphical User Interface
MATLAB contains a nice GUI application that will guide you through importing data from any recognized data file (usually .mat, .txt, or .xls on a Windows system). To use it, go to file > import data, and select the file you want. Then, choose what column separators are present (by selecting the appropriate radio button). Finally, click "next".
MATLAB saves the variable under a name similar to that of the file, but with modifications to make it conform with MATLAB syntax. Spaces are omitted, plusses and minuses are turned into other characters. To see the name MATLAB generated (and probably change it) type "who" in the command prompt.
External Resources
Chapter 3: Data Storage and Manipulation
Data Types and Operations on Point Values
Introduction
A large number of MATLAB's functions are operations on two types of numbers: rational numbers and boolean numbers.
Rational numbers are what we usually think of when we think of what a number is. 1, 3, and 4.5 are all rational numbers. MATLAB stores rational numbers as doubles by default, which is a measure of the number of decimal places that are stored in each variable and thus of how accurate the values are. Note that MATLAB represents irrational numbers such as pi with rational approximations, except when using the symbolic math toolbox. See that section for details.
Boolean numbers are either "TRUE" or "FALSE", represented in MATLAB by a 1 and a 0 respectively. Boolean variables in MATLAB are actually interchangable with doubles, in that boolean operators can be performed with arrays of doubles and vice versa. Any nonzero number in this case is considered "TRUE".
Most of the rational operators also work with complex numbers. Complex numbers; however, cannot be interchanged with boolean values like the real rationals can.
Rational Operators on Single Values
MATLAB has all the standard rational operators. It is important to note, however, that Unless told otherwise, all rational operations are done on entire arrays, and use the matrix definitions. Thus, even though for now we're only talking about operations on a single value, when we get into arrays, it will be important to distinguish between matrix and componentwise multiplication, for example.
Add, Subtract, multiply, divide, exponent operators:
%addition
a = 1 + 2
%subtraction
b = 2  1
%matrix multiplication
c = a * b
%matrix division (pseudoinverse)
d = a / b
%exponentiation
e = a ^ b
The modulo function returns the remainder when the arguments are divided together, so a modulo b means the remainder when a is divided by b.
%modulo
remainder = mod(a,b)
All of these functions except for the modulus work for complex numbers as well.
Relational Operators
Equality '==' returns the value "TRUE" (1) if both arguments are equal. This must not be confused with the assignment operator '=' which assigns a value to a variable.
>> %relational
>>a=5;b=5;
>>a==b
ans = 1
%Assignment
>>a=5;b=3;
>>a=b
a = 3
Note that in the first case, a value of 1 (true) is returned, however for the second case a gets assigned the value of b.
Greater than, less than and greater than or equal to, less than or equal to are given by >, <, >=, <= respectively. All of them return a value of true or false. Example:
>>a=3;b=5;
>>a<=b
ans = 1
>>b<a
ans = 0
Boolean Operators on Single Values
The boolean operators are & (boolean AND)  (boolean OR) and ~ (boolean NOT /negation). A value of zero means false, any nonzero value (usually 1) is considered true.
Here's what they do:
>>%boolean AND
>> y = 1 & 0
y = 0
>> y = 1 & 1
y = 1
>>%boolean OR
>> y = 1  0
y = 1
>> y = 1  1
y = 1
The negation operation in MATLAB is given by the symbol ~, which turns any FALSE values into TRUE and vice versa:
>> c = (a == b)
c = 1
>> ~c
ans = 0
This is necessary because conditionals (IF/SWITCH/TRY) and loops (FOR/WHILE) always look for statements that are TRUE, so if you want it to do something only when the statement is FALSE you need to use the negation to change it into a true statement.
The NOT operator has precedence over the AND and OR operators in MATLAB unless the AND or OR statements are in parenthesis:
>> y = ~1 & 0
y = 0
>> y = ~(1&0)
y = 1
Terminology
MATLAB refers to Booleans as "logicals" and does not use the word "Boolean" in code or documentation.
Declaring Strings
Strings are declared using single quotes:
>> fstring = 'hello'
fstring =
hello
Including a single quote in a string is done this way:
>> fstring = ''''
fstring =
'
>> fstring = 'you''re'
fstring =
you're
Strings as a Character Array
Strings in MATLAB are an array of characters. To see this, executing the following code:
>> fstring = 'hello';
>> class(fstring)
ans = char
Because strings are arrays, many array manipulation functions work including: size, transpose, and so on. Strings may be indexed to access specific elements.
Performing arithmetic operations on character arrays converts them into doubles.
>> fstring2 = 'world';
>> fstring + fstring2
ans = 223 212 222 216 211
These numbers are from the ASCII standard for each character in the array. These values are obtained using the double function to turn the array into an array of doubles.
>> double(fstring)
ans = 104 101 108 108 111
The 'char' function can turn an array of integervalued doubles back into characters. Attempting to turn a decimal into a character causes MATLAB to round down:
>> char(104)
ans = h
>> char(104.6)
ans = h
Special String Functions
Since MATLAB strings are character arrays, some special functions are available for comparing entire strings rather than just its components:
deblank
deblank removes white spaces from the string.
findstr
 findstr(bigstring, smallstring) looks to see if a small string is contained in a bigger string, and if it is returns the index of where the smaller string starts. Otherwise it returns [].
strrep
 strrep(string1, replaced, replacement) replaces all instances of replaced in string1 with replacement
strcmp
Strings, unlike rational arrays, do not compare correctly with the relational operator. To compare strings use the strcmp function as follows:
>> string1 = 'a';
>> strcmp(string1, 'a')
ans = 1
>> strcmp(string1, 'A')
ans = 0
Note that MATLAB strings are case sensitive so that 'a' and 'A' are not the same. In addition the strcmp function does not discard whitespace:
>> strcmp(string1, ' a')
ans = 0
The strings must be exactly the same in every respect.
If the inputs are numeric arrays then the strcmp function will return 0 even if the values are the same. Thus it's only useful for strings. Use the == operator for numeric values.
>> strcmp(1,1)
ans = 0.
Displaying values of string variables
If all you want to do is display the value of a string, you can omit the semicolon as is standard in MATLAB.
If you want to display a string in the command window in combination with other text, one way is to use array notation combined with either the 'display' or the 'disp' function:
>> fstring = 'hello';
>> display( [ fstring 'world'] )
helloworld
MATLAB doesn't put the space in between the two strings. If you want one there you must put it in yourself.
This syntax is also used to concatenate two or more strings into one variable, which allows insertion of unusual characters into strings:
>> fstring = ['you' char(39) 're']
fstring = you're
Any other function that returns a string can also be used in the array.
You can also use the "strcat" function to concatenate strings, which does the same thing as above when you use two strings, but it is especially useful if you are using a cell array of strings because it lets you concatenate the same thing to all of the strings at once. Unfortunately you can't use it to add white space (strcat discards what MATLAB considers extraneous whitespace). Here's the syntax for this use.
>> strCell = {'A', 'B'};
>> strcat(strCell, '_');
ans =
A_
B_
Finally, although MATLAB doesn't have a printf function you can do essentially the same thing by using 1 as your file identifier in the fprintf function. The format identifiers are essentially the same as they are in C.
>> X = 9.2
>> fprintf(1, '%1.3f\n', X);
9.200
The "9.200" is printed to the screen. fprintf is nice compared to display because you don't have to call num2str on all of the numbers in a string  just use the appropriate format identifer in the place you want it.
>> X = 9.2
>> fprintf(1, 'The value of X is %1.3f meters per second \n', X);
The value of X is 9.200 meters per second
Cell arrays of strings
In many applications (particularly those where you are parsing text files, reading excel sheets with text, etc.) you will encounter cell arrays of strings.
You can use the function "iscellstr" to tell if all of the elements in a given cell array are strings or not.
>> notStrCell = {'AA', []};
>> iscellstr(notStrCell)
ans = 0
This is useful since functions that work with cell arrays of strings will fail if provided with something that's not a cell array of strings. In particular, they all fail if any elements of the provided cell array are the empty array ( [] ) which is somewhat frustrating if the provided text file contains empty cells. You must catch this exception before calling cellstr manipulation functions.
Searching a cell array of strings can be done with the "strmatch", "strfind", and "regexp" functions. Strmatch looks for a string within a cell array of strings whose first characters exactly match the string you pass to it, and returns the index of all strings in the array for which it found a match. If you give it the 'exact' option, it will only return the indexes of elements that are exactly the same as what you passed. For example:
>> strCell = {'Aa', 'AA'};
>> strmatch('A', strCell);
ans = 1, 2
>> strmatch('A', strCell, 'exact');
ans = []
>> strmatch('Aa', strCell, 'exact');
ans = 1
Strfind looks for a specific string within a cell array of strings, but it tries to find it in any part of each string. For each element x of the given cell array of strings, it will return an empty array if there is no match found in x and the starting index (remember, strings are arrays of characters) of all matches in x if a match to the query is found.
>> strCell = {'Aa', 'AA'};
>> strfind(strCell, 'A');
ans = % answer is a cell array with two elements (same size as strCell):
1 % Index of the beginning of string "A" in the first cell
1 2 % Index of each instance of the beginning of string "A" in the second cell
>> strfind(strCell, 'a');
ans =
2
[] % 'a' is not found
The "cellfun" / "isempty" combination is very useful for identifying cases where the string was or was not found. You can use the find function in combination with these two functions to return the index of all the cells in which the query string was found.
>> strCell = {'Aa', 'AA'};
>> idxCell = strfind(strCell, 'a');
>> isFound = ~cellfun('isempty', idxCell); % Returns "0" if idxCell is empty and a "1" otherwise
>> foundIdx = find(isFound)
foundIdx = 2
The strfind function also has some other options, such as the option to only return the index of the first or last match. See the documentation for details.
The regexp function works the same way as strfind but instead of looking for strings literally, it tries to find matches within the cell array of strings using regular expressions. Regular expressions are a powerful way to match patterns within strings (not just specific strings within strings). Entire books have been written about regular expressions, so they cannot be covered in as much detail here. However, some good resources online include regularexpresions.info and the MATLAB documentation for the matlabspecific syntax. Note that MATLAB implements some, but not all, of the extended regular expressions available in other languages such as Perl.
Unfortunately, MATLAB does not innately have functions to do common string operations in some other languages such as string splitting. However, it is quite possible to find many of these functions in a google search.
Portable functions are expressions defined once, then called whenever it is needed regardless of the platform. Portable functions include anonymous functions, and function handles. A third form of portable functions which is being phased out is inline functions.
Anonymous Functions
Anonymous functions can be created from the command line without a script.
>> convert_min_to_s = @(t) t*60; >> convert_min_to_s(4) ans = 240
Function Handles
Function handles are doubles serving as an abstract reference to the function. Handles allow an equation to be passed to another function for direct evaluation. Anonymous functions are useful for commandline evaluation or for multiple evaluations in the same mfile.
The ampersat returns the handle of a function either built into Matlab or defined in an Mfile.
>> sum_by_a_different_name = @sum; >> sum_by_a_different_name([3 3]) ans = 6 >> not_sum ([3 3]) ??? Undefined function or method 'not_sum' for input arguments of type 'double'.
Function Handles in mfiles
If you are not familiar with mfiles, then skip this and come back.
A function handle passes an mfile function into another function. This of course lets you have more control over what's passed there, and makes your program more general as it lets you pass any mfile (as long as it meets other requirements like having the right number of input arguments and so on). The functionality is similar to that of function pointers in C++.
To pass an mfile to a function, you must first write the mfile, say something like this:
function xprime = f(t,x) xprime = x;
Save it as myfunc.m. To pass this to another function, say an ODE integrator, use the @ symbol as follows:
>> ode45(@myfunc, [0:15], 1)
One advantage of using function handles over anonymous functions is that you can evaluate more than one equation in the mfile, thus allowing you to do things like solve systems of ODEs rather than only one. Anonymous functions limit you to one equation.
How to write a function that accepts a function handle
Functions can accept function handles. To do this define them as variables in your header, and then call the handles as if they were functions:
% myadd adds two variables together function result = myfunc(func, a, b); result = func(a, b); [in a separate mfile] function sum = myadd(a, b) sum = a+b;
The command you send to myfunc looks like this:
>> result = myfunc(@myadd, 1, 2); result = 3
Inline Functions
Inline functions are currently being phased out. Anonymous functions should be used instead. Inline functions are included here for information purposes.
>> convert_s_to_ms = inline('x*1000','x'); >> convert_s_to_ms(20) ans = 20000
Declaring a complex number in MATLAB
Complex numbers in MATLAB are doubles with a real part and an imaginary part. The imaginary part is declared by using the 'i' or 'j' character. For example, to declare a variable as '1 + i' just type:
>> compnum = 1 + i compnum = 1.000 + 1.000i >> compnum = 1 + j compnum = 1.000 + 1.000i
Note that if you use j MATLAB still displays i on the screen.
Since i is used as the complex number indicator it is not recommended to use it as a variable, since it will assume it's a variable if given a choice.
>> i = 3; %bad idea >> a = 1 + i a = 4
However, since implicit multiplication is not normally allowed in MATLAB, it is still possible to declare a complex number like this:
>> i = 3; >> a = 1i + 1 a = 1.000 + 1.000i
It's best still not to declare i as a variable, but if you already have a long program with i as a variable and need to use complex numbers this is probably the best way to get around it.
If you want to do arithmetic operations with complex numbers make sure you put the whole number in parenthesis, or else it likely will not give the intended results.
Arithmetic operations that create complex numbers
There are several operations that create complex numbers in MATLAB. One of them is taking an even root of a negative number, by definition.
>> (1)^0.5 ans = 0.000 + 1.000i >> (3)^0.25 ans = 0.9306 + 0.9306i
As a consequence of the Euler formula, taking the logarithm of a negative number also results in imaginary answers.
>> log(1) ans = 0 + 3.1416i
In addition, the roots of functions found with the 'roots' function (for polynomials) or some other rootfinding function will often return complex answers.
MATLAB functions to manipulate complex values
First of all, it is helpful to tell whether a given matrix is real or complex when programming, since certain operations can only be done on real numbers. Since complex numbers don't have their own class, MATLAB comes with another function called 'isreal' to determine if a given matrix is real or not. It returns 0 if any of the inputs are complex.
>> A = [1 + i, 3]; >> isreal(A) ans = 0 >> isreal(A(2)) ans = 1
Notice that it is possible to have real and complex numbers in the same array, since both are of class double. The function is set up this way so that you can use this as part of a conditional, so that a block only is executed if all elements of array A are real.
To extract just the real part of a complex variable use the 'real' function. To extract just the complex part use the 'imag' function.
>> real(A) ans = 1 3 >> imag(A) ans = 1 0
One thing you may need to do is perform an operation on the real values of an array but not the complex values. MATLAB does not have a function to directly do this, but the following pair of commands lets you put only the real values into another array:
>> RealIndex = (imag(A) == 0); %if imaginary part is zero then the number is real) >> RealOnly = A(RealIndex) RealOnly = 3
Arrays and Matrices
Introduction to Arrays
An array is the most fundamental data type in MATLAB. In MATLAB, as in many traditional languages, arrays are a collection of several values of the same type. The string and number data type formerly presented are particular cases of arrays.
A matrix is an array with two dimensions. Most arrays have the same data type; however, a cell array is an array with varying data types. If no data type is specified for numbers, then the default data type is the equivalent to the double precision floating point in the C programming language on the same architecture. For example on x86 and powerpc a double has 64 bits.
The following list are pages involving work with MATLAB arrays:
Declaring Arrays
Row and Column Arrays
A row array is created using comma separated values inside brackets:
>> array = [0, 1, 4, 5] array = 0 1 4 5
Sometimes commas are omitted for simple row arrays. Omitting commas is not recommended because in larger more complex arrays whitespaces can be ambiguous. Commas almost always indicate an array is horizontal.
A column array is created using semicolons to separate values:
>> column = [1; 2; 3] column = 1 2 3
Declaring multidimensional arrays
A two dimensional array (or a matrix) is declared with commas separating columns, and semicolons separating rows:
>> matrix = [1, 2, 3; 4, 5, 6] matrix = 1 2 3 4 5 6
Simple matrix manipulation is the basis of many linear algebra computations. To use arrays of more than two dimensions, a matrix has to be extended using indexing.
When declaring arrays in MATLAB all rows and all columns need have same size. If not an error message will be generated:
>> matrix = [1, 2, 3; 4, 5] ??? Error using ==> vertcat All rows in the bracketed expression must have the same number of columns.
Indexing Arrays
Arrays are indexed using integers. To return a single element in a simple array, use a single integer.
>> array = [0, 1, 4, 5]; >> array(3) ans = 4
To return a single element in a two dimensional array one number as a row index and the second as a column index.
>> matrix = [1, 2, 3; 4, 5, 6]; >> matrix(2,2) ans = 5
To return multiple elements in an array an array can be used as an index.
>> array = [0, 1, 4, 5]; >> array([1 3]) ans = 0 4
To return the last element of an array use (end).
>> array = [0, 1, 4, 5]; >> array(end) ans = 5
A range of indexes can be returned using a colon(:)
>> array = [0, 1, 4, 5]; >> array(2:end) ans = 1 4 5
Properties of MATLAB arrays and matrices
Contrary to low level languages such as C, an array in MATLAB is a more high level type of data: it contains various information about its size, its data type, and so on.
>> array = [0,1,4,5]; >> length(array) ans = 4 >> class(array) ans = double
The number of rows and columns of the matrix can be known through the builtin size function. Following the standard mathematical convention, the first number is the number of rows and the second is the number of columns:
>> matrix = [1, 2, 3; 4, 5, 6]; >> size(matrix) ans = 2 3
The goal of MATLAB arrays is to have a type similar to mathematical vectors and matrices. As such, row and column arrays are not equivalent. Monodimensional arrays are actually a special case of multidimensional arrays, and the 'size' function can be used for them as well.
>> size(array) ans = 1 4
Row and column do not have the same size, so they are not equivalent:
>> size(column) ans = 3 1 >> size(row) ans = 1 3
Why Use Arrays?
A major advantage of using arrays and matrices is that it lets you avoid using loops to perform the same operation on multiple elements of the array. For example, suppose you wanted to add 3 to each element of the array [1,2,3]. If MATLAB didn't use arrays you would have to do this using a FOR loop:
>> array = [1,2,3]; >> for ii = 1:3 array(ii) = array(ii) + 3; >> end >> array array = [4,5,6]
Doing this is not efficient in MATLAB, and it will make your programs run very slowly. Instead, you can create another array of 3s and add the two arrays directly. MATLAB automatically separates the elements:
>> array = [1,2,3]; >> arrayofthrees = [3,3,3]; >> array = array + arrayofthrees array = [4,5,6];
If all you are doing is adding a constant, you can also omit the declaration of 'arrayofthrees', as MATLAB will assume that the constant will be added to all elements of the array. This is very useful, for example if you use an array with variable size:
>> array = [1,2,3]; >> array + 3 ans = [4,5,6]
The same rule applies to scalar multiplication.
See Introduction to array operations for more information on the operations MATLAB can perform on arrays.
Arrays are a fundamental principle of MATLAB, and almost everything in MATLAB is done through a massive use of arrays. To have a deeper explanation of arrays and their operations, see Arrays and matrices.
Introduction to array operations
As arrays are the basic data structure in MATLAB, it is important to understand how to use them effectively. See the previous section for that.
Arrays in MATLAB obey the same rule as their mathematical counterpart: by default, the matrix definitions of operations are used, unless a special operator called the dot operator is applied.
Because arrays operations are so similar to the equivalent mathematical operations, a basic knowledge of linear algebra is mandatory to use matlab effectively. However, we won't be as precise as in mathematics when using the terms vector and matrix. In MATLAB, both are arrays of doubles (thus being a matrix in the real mathematical meaning), and MATLAB considers vectors as a matrices with only one row or only one column. However, there are special functions just for vectors; see the vector module for an explanation of how to use these.
Basics
Accessing elements of a matrix
Using a Single Index
Now that you know how to define a simple array, you should know how to access its elements. Accessing the content of an array is done through the operator (), with the index inside the parenthesis; the indexing of the first element is 1:
>> a = [1, 2, 3]; >> a(1) ans = 1
>> a(3) ans = 3
Accessing an element outside the bounds will result in an error:
>> a(5) ??? Index exceeds matrix dimensions.
Using Multiple Indexes
To access a single matrix element, you can use the (i,j) subscript, where i is the index in the row, and j in the column:
>> a= [1, 2; 3, 4]; >> a(1, 2) ans = 2 >> a(2, 1) ans = 3
Using A Unique Index
You can also access a matrix element through a unique index; in this case, the order is column major, meaning you first go through all elements of the first column, then the 2d column, etc... The column major mode is the same as in Fortran, and the contrary of the order in the C language.
>> a = [1, 2, 3; 4, 5, 6]; >> a(3) ans = 2
Using a Colon (:) for a Block Index
It is also possible to access blocks of matrices using the colon (:) operator. This operator is like a wildcard; it tells MATLAB that you want all elements of a given dimension or with indices between two given values. For example, say you want to access the entire first row of matrix a above, but not the second row. Then you can write:
>> a = [1, 2, 3; 4, 5, 6]; >> a(1,:) %row 1, every column ans = 1 2 3
Now say you only want the first two elements in the first row. To do this, use the following syntax:
>> a = [1, 2, 3; 4, 5, 6]; >> a(1, 1:2) ans = 1 2
The syntax a(:) changes a into a column vector (column major):
>> a = [1, 2, 3; 4, 5, 6] >> a(:) ans = 1 4 2 5 3 6
Using the end Operator
Finally, if you do not know the size of an array but wish to access all elements from a certain index until the end of the array, use the end operator, as in
>> a = [1, 2, 3; 4, 5, 6] >> a(1, 2:end) %row 1, columns from 2 until end of the array ans = 2 3
Logical Addressing
In addition to index addressing, you can also access only elements of an array that satisfy some logical criterion. For example, suppose a = [1.1, 2.1, 3.2, 4.5] and you only want the values between 2 and 4. Then you can achieve this in two ways. The first is to use the find function to find the indices of all numbers between 2 and 4 in the array, and then address the array with those indices:
>> a = [1.1, 2.1, 3.2, 4.5]; >> INDICES = find(a >= 2 & a <= 4); >> a(INDICES) ans = 2.1 3.2
This does not work in MATLAB 2006b.
The second method is to use logical addressing, which first changes a into a logical array, with value 1 if the logical expression is true and 0 if it is false. It then finds and returns all values in the a which are true. The syntax for this is as follows:
>> a = [1.1, 2.1, 3.2, 4.5]; >> a(a >= 2 & a <= 4) ans = 2.1 3.2
Basic operations
Rational Operators on Arrays
Addition and Subtraction
The interesting part is of course applying some operations on those arrays. You can for example use the classic arithmetic operations + and  on any array in matlab: this results in the vector addition and subtraction as defined in classic vector vectors spaces , which is simply the addition and subtraction elements wise:
>> [1, 2, 3]  [1, 2, 1] ans = 0 0 2
Multiplication by a Scalar
The multiplication by a scalar also works as expected:
>> 2 * [1, 2, 3] ans = [2, 4, 6]
Multiplying and Dividing Arrays
Multiplication and division are more problematic: multiplying two vectors in does not make sense. It makes sense only in the matrix context. Using the symbol * in matlab computes the matrix product, which is only defined when the number of columns of the left operand matches the number of rows of the right operand:
>> a = [1, 2; 3, 4]; >> a * a ans =
7 10 15 22
>> a = [1, 2, 3]; b = [1; 2; 3]; >> a * a ??? Error using ==> * Inner matrix dimensions must agree. >> a * b ans = 14
Using the division symbol / has even more constraints, as it imposes the right operand to be invertible (see Wikipedia:Invertible matrix). For square matrices, is equivalent to . For example :
>> a = [1, 2; 3, 4]; b = [1, 2; 1, 2] >> b / a ans = 1 0 1 0
>> a / b Warning: Matrix is singular to working precision. ans = Inf Inf Inf Inf
Componentwise Operations
If you desire to multiply or divide two matrices or vectors componentwise, or to raise all components of one matrix to the same power, rather than using matrix definitions of these operators, you can use the dot (.) operator. The two matrices must have the same dimensions. For example, for multiplication,
>> a = [1, 2, 3]; >> b = [0, 1, 2]; >> a .* b ans = 0 2 6
The other two componentwise operators are ./ and .^.
As matlab is a numerical computing language, you should keep in mind that a matrix which is theoretically invertible may lead to precision problems and thus giving imprecise results or even totally wrong results. The message above "matrix is singular to working precision" should appear in those cases, meaning the results cannot be trusted.
Nonsquare matrices can also be used as the right operand of /; in this case, it computes the pseudoinverse. This is especially useful in least square problems.
Transpose
A transpose of a matrix is taken using .'
>> array = [1,2;3,4] array = 1 2 3 4 >> array.' ans = 1 3 2 4
Boolean Operators on Arrays
The same boolean operators that can be used for point values can also be used to compare arrays. To do this, MATLAB compares the elements componentwise and returns them in a logical array of the same size as the two arrays being compared. The two arrays must have the same size. For example,
>> A = [2,4], B = [1,5]; >> A < B ans = [0 1]
You must be careful when using comparisons between arrays as loop conditions, since they clearly do not return single values and therefore can cause ambiguous results. The loop condition should be reducable to a single boolean value, T or F, not an array. Two common ways of doing this are the "any" and the "all" functions. A function call any(array) will return true if array contains any nonzero values and false if all values are zero. It does the comparisons in one direction first then the other, so to reduce a matrix you must call the any function twice. The function all, similarly, returns true if and only if all elements in a given row or column are nonzero.
Concatenating Arrays
Concatenating arrays involves sticking arrays together.
Horizontal Concatenating
Horizontal concatenation is done by treating an array as if it were a variable included in a row.
>> a = [1,2;3,4]; >> b = [5,6;7,8]; >> c = [a,b] c = 1 2 5 6 3 4 7 8
Vertical Concatenating
Vertical concatenation is done by treating an array as if it were a variable included in a column.
>> a = [1,2;3,4]; >> b = [5,6;7,8]; >> c = [a;b] c = 1 2 3 4 5 6 7 8
Solving Linear Systems
To solve a linear system in the form Ax = b use the "\" operator.
Example:
>>A = [4 5 ; 2 8]; b = [23 28]'; x = A\b x = 2 3
A vector in MATLAB is defined as an array which has only one dimension with a size greater than one. For example, the array [1,2,3] counts as a vector. There are several operations you can perform with vectors which don't make a lot of sense with other arrays such as matrices. However, since a vector is a special case of a matrix, any matrix functions can also be performed on vectors as well provided that the operation makes sense mathematically (for instance, you can matrixmultiply a vertical and a horizontal vector). This section focuses on the operations that can only be performed with vectors.
Declaring a vector
Declare vectors as if they were normal arrays, all dimensions except for one must have length 1. It does not matter if the array is vertical or horizontal. For instance, both of the following are vectors:
>> Horiz = [1,2,3]; >> Vert = [4;5;6];
You can use the isvector function to determine in the midst of a program if a variable is a vector or not before attempting to use it for a vector operation. This is useful for error checking.
>> isvector(Horiz) ans = 1 >> isvector(Vert) ans = 1
Another way to create a vector is to assign a single row or column of a matrix to another variable:
>> A = [1,2,3;4,5,6]; >> Vec = A(1,:) Vec = 1 2 3
This is a useful way to store multiple vectors and then extract them when you need to use them. For example, gradients can be stored in the form of the Jacobian (which is how the symbolic math toolbox will return the derivative of a multiple variable function) and extracted as needed to find the magnitude of the derivative of a specific function in a system.
Declaring a vector with linear or logarithmic spacing
Suppose you wish to declare a vector which varies linearly between two endpoints. For example, the vector [1,2,3] varies linearly between 1 and 3, and the vector [1,1.1,1.2,1.3,...,2.9,3] also varies linearly between 1 and 3. To avoid having to type out all those terms, MATLAB comes with a convenient function called linspace to declare such vectors automatically:
>> LinVector = linspace(1,3,21) LinVector = Columns 1 through 9 1.0000 1.1000 1.2000 1.3000 1.4000 1.5000 1.6000 1.7000 1.8000 Columns 10 through 18 1.9000 2.0000 2.1000 2.2000 2.3000 2.4000 2.5000 2.6000 2.7000 Columns 19 through 21 2.8000 2.9000 3.0000
Note that linspace produces a row vector, not a column vector. To get a column vector use the transpose operator (') on LinVector.
The third argument to the function is the total size of the vector you want, which will include the first two arguments as endpoints and n  2 other points in between. If you omit the third argument, MATLAB assumes you want the array to have 100 elements.
If, instead, you want the spacing to be logarithmic, use the logspace function. This function, unlike the linspace function, does not find n  2 points between the first two arguments a and b. Instead it finds n2 points between 10^a and 10^b as follows:
>> LogVector = logspace(1,3,21) LogVector = 1.0e+003 * Columns 1 through 9 0.0100 0.0126 0.0158 0.0200 0.0251 0.0316 0.0398 0.0501 0.0631 Columns 10 through 18 0.0794 0.1000 0.1259 0.1585 0.1995 0.2512 0.3162 0.3981 0.5012 Columns 19 through 21 0.6310 0.7943 1.0000
Both of these functions are useful for generating points that you wish to evaluate another function at, for plotting purposes on rectangular and logarithmic axes respectively.
Vector Magnitude
The magnitude of a vector can be found using the norm function:
>> Magnitude = norm(inputvector,2);
For example:
>> magHoriz = norm(Horiz) magHoriz = 3.7417 >> magVert = norm(Vert) magVert = 8.7750
The input vector can be either horizontal or vertical.
Dot product
The dot product of two vectors of the same size (vertical or horizontal, it doesn't matter as long as the long axis is the same length) is found using the dot function as follows:
>> DP = dot(Horiz, Vert) DP = 32
The dot product produces a scalar value, which can be used to find the angle if used in combination with the magnitudes of the two vectors as follows:
>> theta = acos(DP/(magHoriz*magVert)); >> theta = 0.2257
Note that this angle is in radians, not degrees.
Cross Product
The cross product of two vectors of size 3 is computed using the 'cross' function:
>> CP = cross(Horiz, Vert) CP = 3 6 3
Note that the cross product is a vector. Analogous to the dot product, the angle between two vectors can also be found using the cross product's magnitude:
>> CPMag = norm(CP); >> theta = asin(CPMag/(magHoriz*magVert)) theta = 0.2257
The cross product itself is always perpendicular to both of the two initial vectors. If the cross product is zero then the two original vectors were parallel to each other.
Introduction to Structures
MATLAB provides a means for structure data elements. Structures are created and accessed in a manner familiar for those accustomed to programming in C.
MATLAB has multiple ways of defining and accessing structure fields. See Declaring Structures for more details.
Note: Structure field names must begin with a letter, and are casesensitive. The rest of the name may contain letters, numerals, and underscore characters. Use the namelengthmax function to determine the maximum length of a field name.
Declaring Structures
Structures can be declared using the struct command.
>> a = struct('b', 0, 'c', 'test') a = b: 0 c: 'test'
In MATLAB, variables do not require explicit declaration before their use. As a result structures can be declared with the '.' operator.
>> a.c = 'test' a = c: 'test'
Structures can be declared as needed and so can the fields.
Arrays of Structures
Structures can also be arrays. Below is an example
>> a = struct('b', 0, 'c', 'test'); % Create structure >> a(2).b = 1; % Turn it into an array by creating another element >> a(2).c = 'testing' a = 1x2 struct array with fields: b c >> a(1) % Initial structure ans = b: 0 c: 'test' >> a(2) % The second element ans = b: 1 c: 'testing'
Accessing Fields
When the field name is known the field value can be accessed directly.
>> a.c ans = test ans = testing
In some cases you may need to access the field dynamically which can be done as follows.
>> str = 'c'; >> a(1).(str) ans = test >> a(1).c ans = test
Accessing Array Elements
Any given element in a structure array can be accessed through an array index like this
>> a(1).c ans = test
To access all elements in a structure array use the syntax {structure.field}. In order to get all values in a vector or array use square brackets ([]) as seen below.
>> [a.('c')] ans = testtesting >> [a.('b')] ans = 0 1
Or you can put them all into a cell array (rather than concatenating them) like this:
>> {a.('c')} ans = {'test', 'testing'}
Assigning values to a field of each struct array element
Matlab provides tools to assign values to a field of each array element. Consider the following struct array:
foo = struct('field_a',{1,2,3,4}, 'field_b',{4,8,12,16})
The following command assigns the same value to the field_b field of each array element:
value = 1;
[foo.field_b] = deal(value)
To assign different values to each array element:
value = {4,8,12,16};
[foo.field_b] = value{:}
Subarrays through logical addressing
With Matlab, it's possible to extract a subarray from an array by using logical indexing. Consider the following struct array:
foo = struct('field_a',{1,2,3,4},'field_b',{4,8,12,16})
To obtain a subarray from foo where all foo.field_a values are equal to 2, a boolean array can be used to perform logical indexing. So, a boolean test that returns a boolean array for this purpose would be:
[foo.field_a] == 2
So, by using this boolean array to perform logical indexing, Matlab defines a struct array whose elements consist of those from foo whose field_a value is equal to 2 by doing:
foo([foo.field_a] == 2)
Cell Array Introduction
Cell Arrays can contain differing information in every element. These types of arrays are useful when interacting with spreadsheet software.
Creating Cell Arrays
Cell arrays follow the same conventions as regular arrays except instead of square brackets use curly brackets.
array = [1, 2, 3; 4, 5, 6]; cell_array = {1, 2, 3; 4, 5, 6};
Cell arrays have fewer limitations than regular arrays. The regular array can hold strings; however, the string in each element must be the same length. If one element in a regular array is a string then all elements must be a string. Cell arrays have neither of these limitations.
cell_array = {1, 2, 'a', 'abc'; rand(3, 2), magic(3), eye(3), 'junk'} cell_array = [ 1] [ 2] 'a' 'abc' [3x2 double] [3x3 double] [3x3 double] 'junk'
With fewer limitations for the content of a cell array comes complications. While cell arrays are a powerful tool, these arrays work differently because each element can be almost anything.
Dynamic Resizing
Cell arrays can be dynamically resized, which is a key feature in more advanced data structures. For example, a queue data structure using the commands:
cell_array{end+1}='a'; cell_array{end+1}='b';
An element can be popped from the front of the queue using the commands:
cell_array(1)=[]; % remove first element  resize cell_array(1)=[]; % remove first element  resize
Uses
GUI Tables
Cell arrays are used when displaying a table to a figure.
uitable('Data',{'hello',1;2,'there'})
Converting to and from cell arrays
Converting From a Numeric Array into a Cell Array
Use num2cell to convert from a numeric into a cell array.
>> cell_array = num2cell(numeric_array);
Converting From a Cell Array into a Numeric Array
Use cell2mat to convert from a cell into a numeric array.
>> numeric_array = cell2mat(numeric_cell_array);
External Links
ControlTheoryPro.com MATLAB Programming/Sparce Matrices
Chapter 4: Graphics
2D Graphics
Plot
The plot command renders a 2D line in Cartesian coordinates.
Example:
x=0:0.1:2; % Creates a vector from 0 to 2, spaced by 0.1.
fx=(x+2)./x.^2; % calculates fx based on the values stored in x
plot(x,fx) % Plots 2D graphics of the function fx
Matlab also lets the user specify the line style. The following example generates the same graph as in the previous example, but plots the function with a specific line style: a black line with circle markers on each node:
x=linspace(0, 2, 21); % like the previous example, creates a vector from 0 to 2, spaced by 0.1
fx= arrayfun(@(x) (x+2)/x^2, x); % like the previous example, calculates fx based on the values stored in x
plot(x,fx,'ok') % Plots the graph of (x, fx) as a black line with circle markers at each point
To plot two or more graphs in one figure, simply append the second (x,y) pair to the first: The following example will plot y1 and y2 on the same xaxis in the output.
x1 = [1,2,3,4]
y1 = [1,2,3,4]
y2 = [4,3,2,1]
plot(x1,y1,x1,y2)
Polar Plot
Plots a function using θ and r(θ)
t = 0:.01:2*pi;
polar(t,sin(2*t).^2)
3D Graphics
plot3
The "plot3" command is very helpful and makes it easy to see threedimensional images. It follows the same syntax as the "plot" command. If you search the MATLAB help (not at the command prompt. Go to the HELP tab at the top of the main bar and then type plot3 in the search), you will find all the instruction you need.
Example:
l=[98.0556 ; 1187.074];
f=[ 33.5448 ; 240.402];
d=[ 1298 ; 1305.5]
plot3(l,f,d); grid on;
This example plots a line in 3D. I created this code in an Mfile. If you do the same, change the values and hit the run button in the menu bar to see the effect.
Mesh
Creates a 3D plot using vectors x and y, and a matrix z. If x is n elements long, and y is m elements long, z must be an m by n matrix.
Example:
x=[0:pi/90:2*pi]';
y=x';
z=sin(x*y);
mesh(x,y,z);
Contour
Creates a 2D plot of a 3D projection, using vectors x and y, and a matrix z. If x is n elements long, and y is m elements long, z must be an m by n matrix.
Example:
x=[0:pi/90:2*pi]';
y=x';
z=sin(x*y);
contour(x,y,z);
Contourf
Same as contour, but fills color between contour lines
Surface
Basically the same as mesh MATLAB offers incomparable control over the way you can add details to your plot. From inserting text at the right positions to labelling the axes, MATLAB from the command line offers you an easy way to create publication style graphics. With support for Encapsulated PostScript and Adobe Illustrator output. Complex figures with several axes and conveying large amounts of information can be created.
Concept of a handle
Most operations on figures generate objects with a set of properties. Users familiar with objectoriented programming would realize that the functions and the data are encapsulated into the object. A typical figure would contain at least half a dozen objects. These objects are called handles. A very tacky analogy would be like handles to several different refrigerators with several different contents. To provide an intuitive feel. I have listed out the properties from a text handle.
Finding a handle
Various commands provide required handles, for example:
h = gcf; % Get current figure h = gca; % Get current axis
Examples
Axis Label
xlabel labels the xaxis of the current plot.
>>xlabel('string')
You can display text on two lines or insert the value of variables
>>xlabel({['First Line or line n° ',int2str(a)],['Second Line or line n°',int2str(b)]})
ylabel labels the yaxis of the current plot. It works in same way of xlabel, but the output is vertical in 2D plots.
Documenting a Maximum Value
% Previous code set the x value of the peak data point into x_peak plot(lags(1:1000:end),abs_cs(1:1000:end)); ptitle = 'UUT and Source Correlation Score Magnitude'; xlabel('Lag'); ylabel('Correlation Magnitude'); title(ptitle); yloc = max(get(gca,'YLim')); % Put at top of plot text(lags(x_peak),yloc,[' \leftarrow ' num2str(x_peak) 'ns']); lstr{1} = sprintf(' Test %d', TESTNUM); lstr{2} = sprintf(' Unit %d%s', UNITNUM, comparestr); text(lags(1),mean(get(gca,'YLim')),lstr);
Chapter 5: M File Programming
Mfiles
There are 2 types of mfile
 Scripts
 Functions
Scripts are a type of mfile that runs in the current workspace. So if you call a script from the command line (base workspace) the script will use and manipulate the variables of the base workspace. This can get very messy and lead to all sorts of strange errors when loops are involved and the coder is lazy about naming their loop variables (i.e. for i = 1:10, if every loop uses i, j, or k then it's likely that any script called from a loop will alter the loop variable).
Functions are wholly contained in themselves. They possess their own workspace keeping workspaces separate. This means that all variables necessary for a particular function must be passed or defined in some way. This can get tedious for complex algorithms requiring lots of variables. However, any manipulations of variables are discarded when the function is exited. Only those output arguments provided by the function are available to the calling workspace. This means that loops can use i, j, or k all they want because the function's workspace and the calling workspace do not mix.
Any command valid at the command line is valid in any mfile so long as the necessary variables are present in the mfiles operating workspace.
Using functions properly any change can be affected to any algorithm or plotting tool. This allows for automation of repetitive tasks.
It is optional to end the Mfile with 'end'; doing so, however, can lead to complications if you have conditionals or loops in your code, or if you're planning on using multiple functions in the same file (see nested functions for details on this).
Requirements for a function
Custom functions follow this syntax in their most basic form:
function [output1, output2, ...]= function_name(input_arg1,input_arg2) statements return;
In current versions of MATLAB the return; line is not required. The function_name can be anything you like but it is best if the mfile name is function_name.m. Calling the function from the command line or another mfile is done by invoking the mfile name of the function with the necessary input and output arguments.
Within the function itself, there must be a statement that defines each of the output arguments (output1, output2, etc.). Without some declaration the variable for the output argument doesn't exist in the function's workspace. This will cause an error about "one or more output arguments". It is good practice to initialize the output arguments at the beginning of the function.
Typically output arguments are initialized to empty ([]) or 0 or 1 or something equivalent for other data types. The reason is that if the function encounters an error you've anticipated then the function can return (via the return command) with those default values. If the initialization value is an invalid value then it can easily be checked by the calling function for any errors which may not throw a MATLAB error.
Path
In order to invoke a function, that function's mfile must be in the current path. There is a default path that can be set up through the File menu or the addpath command. The order of the path is important as MATLAB searches the path in order and stops searching after it finds the first instance of that mfile name.
The current path is
 the current directory (which can be seen at the top of the MATLAB window or by typing pwd at the command prompt
 the default path
Note that MATLAB will always search the current directory before searching any of the rest of the path.
nargin & nargout
The nargin and nargout commands are only valid inside functions since scripts are not passed any arguments. The nargin command returns the number of passed input arguments. This is useful in conjunction with nargchk
nargchk(min, max, nargin)
where min is the minimum number of arguments necessary for the function to operate and max is the maximum number of valid input arguments.
The nargout command is useful for determining which output arguments to return. Typically, the outputs are the end results of some algorithm and they are easily calculated. However, in some instances secondary output arguments can be time consuming to calculate or require more input arguments than the primary output arguments do. So the function can check the number of output arguments being requested through the nargout command. If the caller isn't saving the secondary output arguments then they do not need to be calculated.
varargin & varargout
When using MATLAB objects and functions they often allow the user to set properties. The functions and objects come with default values for these properties but the user is allowed to override these defaults. This is accomplished through the use of varargin. varargin is a cell array that is usually parsed where varargin{i} is a property and varargin{i+1} is the value the user wishes for that property. The parsing is done with a for or while loop and a switch statement.
function [out] = myFunc(in, varargin)
The varargout output argument option allows for a variable number of output arguments just as varargin allows for a variable number of input arguments. From the MATLAB site
function [s,varargout] = mysize(x) nout = max(nargout,1)1; s = size(x); for k=1:nout, varargout(k) = {s(k)}; end
returns the size vector and, optionally, individual sizes. So
[s,rows,cols] = mysize(rand(4,5));
returns s = [4 5], rows = 4, cols = 5.
Useful syntax guidelines
Placing the semicolon symbol after every line tells the compiler not to place that line of code in the command prompt and then execute. This can make your programs run a lot faster. Also, placing a semicolon after every line helps with the debugging process.
syms x y z; w=[x y z]; e=[1 2 3]; t=jacobian(e,w);
Placing comments in your code can help other people (and yourself) understand your code as it gets more complex.
syms x y z; %syms command makes x y and z symbolic w=[x y z]; e=[1 2 3]; t=jacobian(e,w);
Comments can also Identify who wrote the code and when they wrote it.
%Some code writer %mm/dd/yyyy
See the 'comments' section for more details on this.
Nested functions
External Links
Large parts of this page come from the ControlTheoryPro.com page on Mfiles, Scripts, and Functions.
Placing comments
Comment lines begin with the character '%', and anything after a '%' character is ignored by the interpreter. The % character itself only tells the interpreter to ignore the remainder of the same line.
In the MATLAB Editor, commented areas are printed in green by default, so they should be easy to identify. There are two useful keyboard shortcuts for adding and removing chunks of comments. Select the code you wish to comment or uncomment, and then press CtrlR (⌘/ for Mac) to place one '%' symbol at the beginning of each line and CtrlT (⌘T for Mac) to do the opposite.
MATLAB also supports multiline comments, akin to /* ... */
in languages like C or C++, via the %{
and %}
delimiters. But there is a small and important difference. In MATLAB it is not allowed that the lines starting with %{
or %}
contains any other text (except white spaces). Otherwise it would not work. E.g.
%{ for i = 1:10 disp(i) end %}
gives an error, but
%{ for i = 1:10 disp(i) end %}
works just fine.
Common uses
Comments are useful for explaining what function a certain piece of code performs especially if the code relies on implicit or subtle assumptions or otherwise perform subtle actions. Doing this is a good idea both for yourself and for others who try to read your code. For example,
% Calculate average velocity, assuming acceleration is constant % and a frictionless environment. force = mass * acceleration
It is common and highly recommended to include as the first lines of text a block of comments explaining what an M file does and how to use it. MATLAB will output the comments leading up to the function definition or the first block of comments inside a function definition when you type:
>> help functionname
All of MATLAB's own functions written in MATLAB are documented this way as well.
Comments can also be used to identify authors, references, licenses, and so on. Such text is often found at the end of an M file though also can be found at the beginning. Finally, comments can be used to aid in debugging, as explained in Debugging M Files.
The input() function lets your scripts process data entered at the command line. All input is converted into a numerical value or array. The argument for the input() function is the message or prompt you want it to display. Inputting strings require an additional 's' argument. Example:
%test.m
%let's ask a user for x
x = input('Please enter a value for x:')
Then running the script would produce the output:
Please enter a value for x:3
x = 4
>>
Control Flow
IF statement
An IF statement can be used to execute code when the logical test (expression) returns a true value (anything but 0). An "else" statement following an "if" statement is executed if the same expression is false (0).
Syntax:
if expression statements elseif expression2 statements end
SWITCH statement
Switch statements are used to perform one of several possible sets of operations, depending on the value of a single variable. They are intended to replace nested "if" statements depending on the same variable, which can become very cumbersome. The syntax is as follows:
switch variable case value1 statements(1) case value2 statements(2) ... otherwise statements end
The end is only necessary after the entire switch block, not after each case. If you terminate the switch statement and follow it with a "case" statement you will get an error saying the use of the "case" keyword is invalid. If this happens it is probably because you deleted a loop or an "if" statement but forgot to delete the "end" that went with it, thus leaving you with surplus "end"s. Thus MATLAB thinks you ended the switch statement before you intended to.
The otherwise keyword executes a certain block of code (often an error message) for any value of variable other than those specified by the "case" statements.
Programmers who are used to C style languages, often put break statements after each case. In C, C++, and Java, not putting a break statement allows the code to fall through in the code above, if value1 is true, then statements(1), statements(2), etc., will execute in Cstyle languages. However, in MATLAB only statements(1) will execute.
TRY/CATCH statement
The TRY/CATCH statement executes a certain block of code in the "try" block. If it fails with an error or a warning, the execution of this code is terminated, and the code in the "catch" block is executed rather than simply reporting an error to the screen and terminating the entire program. This is useful for debugging and also for filtering out erroneous calculations, like if you accidentally try to find the inverse of a singular matrix, when you don't wish to end the program entirely.
Syntax:
try statements catch statements end
Note that unlike the other control flow statements, the TRY/CATCH block does not rely on any conditions. Therefore the code in the TRY block will always be at least partially executed. Not all of the TRY block code will always be executed, since execution of the TRY ends when an error occurs. In addition, the statements in the CATCH block will never be executed if the TRY block does not fail.
FOR statement
The FOR statement executes code a specified number of times using an iterator. Syntax:
for iterator = startvalue:increment:endvalue statements end
The iterator variable is initialized to startvalue and is increased by the amount in increment every time it goes through the loop, until it reaches the value endvalue. If increment is omitted, it is assumed to be 1, as in the following code:
for ii = 1:3 statements end
This would execute statements three times.
WHILE statement
The while statement executes code until a certain condition evaluates to false or zero. Example:
while condition statements end
Forgetting to change the condition within a while loop is a common cause of infinite loops.
BREAK, CONTINUE, and RETURN
MATLAB includes the "break" and "continue" keywords to allow tighter loop control. The "break" keyword will cause the program to leave the loop it is currently in and continue from the next line after the loop ends, regardless of the loop's controlling conditions. If the code is in a nested loop it only breaks from the loop it's in, not all of them. The syntax is simply to write the word "break" within the loop where you desire it to break.
In contrast to "break", "continue" causes the program to return back to the beginning of the loop it is presently in, and to recheck the condition to see if it should continue executing loop code or not. The code in the loop after the "continue" statement is not executed in the same pass.
If you want to exit a function entirely (as opposed to just a loop) before the last line of code, it is possible to do so using the "return" keyword. The value of any output variables is immediately returned to the calling function. As an example of how this works, consider the following function:
function output = controlTest(doWhat) switch doWhat case 1 output = 1; return; case 2 output = 3; end output = output + 4; end
Calling
>> output = controlTest(1)
would return output = 1, because output is defined to 1 and the return statement tells MATLAB to immediately take the current value of output and pass it back to the calling function. However, calling
>> output = controlTest(2)
would return output = 7, because output is initially defined as 3 and then 4 is added to it. Since the return statement is only executed in the case that doWhat=1, it is not called and the rest of the function executes.
Beware that if the output variables are not defined before calling the return statement, you will get an error, so use this with some degree of caution.
Program Flow
The idea of program flow is simple. However, implementing and using flow techniques effectivly takes practice. MATLAB flow control is almost identical to flow control in C. There is a tremendous amount of text on the subject of flow in C. If you do a little homework in about an hour you can know all you need to from one of numerous C tutorials. To be good at flow control all you have to do is practice.
Here are a few concepts that you can practice using flow control to implement:
 Calculate compounding interest using a while loop (don't cheat by using the algebraic form).
 Create a moving average filter using a for loop
 Make a counter that keeps track of keystrokes:How many times a typist hits a certain letter.
MATLAB Programming/Loops and Caveats
As far as I've seen there is little help out there to help people decipher MATLAB's error messages. Most of the syntax errors are not difficult to fix once you know what is causing them so this is intended to be a guide to identifying and fixing errors in MATLAB code.
Warnings are also shown here as these often lead to errors later.
Arithmetic errors
Usually these are selfexplanatory. As a reminder, here are some common functions that cannot be performed and what MATLAB returns (along with a warning for each one):
a/0 = Inf if a > 0, Inf if a < 0, and NaN if a = 0. log(0) = Inf MATLAB defines 0^0 to be 1.
NaN will very often result in errors or useless results unless measures are taken to avoid propagating them.
???Error using ==> minus Matrix dimensions must agree.
So check the dimensions of all the terms in your expression. Often it is an indexing mistake that causes the terms to be of different size. If you are using power function you might add a single dot after the parameter. i.e. y=x.^2 instead of y=x^2
Matrix multiplication requires the number of columns in the first matrix to equal the number of rows in the second. Otherwise, you get the message:
??? Error using ==> mtimes Inner matrix dimensions must agree.
Note the difference between this error and the previous one. This error often occurs because of indexing issues OR because you meant to use componentwise multiplication but forgot the dot.
Attempting to take the inverse of a singular matrix will result in a warning and a matrix of Infs. It is wise to calculate the determinant before attempting to take the inverse or, better, to use a method that does not require you to take the inverse since its not numerically stable.
Attempting to take a power of a nonsquare matrix results in the error
??? Error using ==> mpower Matrix must be square.
This is usually because you meant to use componentwise exponentiation and forgot the dot.
Array Indexing errors
Array indexing is a key component of MATLAB. One feature is that the names of variables and functions are case sensitive, and that one can alias builtin or userwritten functions with variables of the same name. So, if you make an array called abs and you try to call the function abs(1), MATLAB will return the first value in the array abs instead of the value 1. MATLAB will not return an error for this as it is not possible to know for certain that the aliasing of the function wasn't intentional. Hence, never ever name your variables the same as an existing MATLAB function. Unfortunately, there are so many supplied functions in the base product plus installed toolboxes, remembering all of them is impossible so use which proposedname if you have any doubt the name might be in use previously before defining a new array or function. Later versions of MATLAB with the command completion feature will show the short help information after the opening parenthesis or tabcompletion options, using which will aid in avoiding such errors before they arise later in execution by not creating the alias.
Some things are rather obvious but take some practice in avoiding:
You cannot try to access part of an array that does not exist yet.
>> A = [1,3]; >> A(3) ??? Index exceeds matrix dimensions.
Unfortunately, MATLAB doesn't tell you which variable you exceeded the dimensions on if there's more than one so you'll have to check that. This often occurs if, for example, you are using a loop to change which part of an array is accessed, but the loop doesn't stop before you reach the end of the array. This also happens if you end up with an empty matrix as a result of some operation and then try to access an element inside it.
You cannot try to access a negative, complex, noninteger, or zero part of an array; if you do you get this message:
>> A(1) >> A(i) >> A(1.5) >> A(0) ??? Subscript indices must either be real positive integers or logicals.
Note that MATLAB arrays are 1based, not 0based and are fixed lower dimension, not variable. MATLAB may be able to tell you which index is not real or logical depending on context.
>> y=3*A(1) Attempted to access A(1); index must be a positive integer or logical.
The latter being an expression is parsed differently and so has the actual array available in the error message.
Also note that if 0 were a logical 0 (false) then the statement A(0) would not be an indexing error but a logical subscripting expression. In this case the return would be the empty [] array as there are no subscripts matching false in the defined set of [1 2] as A has been defined above. A more useful expression would be something like
>> A(A==3)
Attempting to use nonstandard MATLAB syntax in your indexing will often result in the error:
>> A(2::, 2) ??? A(2::, 2)  Error: Unexpected MATLAB operator.
The above could be an example of someone trying to access all rows of A after the first one and the second column, in which case you should use the "end" syntax, as in:
>> A(2:end, 2) ans = 3
Assignment errors
Ah, assignment, that is using the = sign to give a variable, or certain elements of an array, a particular value.
Let's start with a classic mistake:
>> a = 2; >> if a = 3 ??? if a = 3  Error: The expression to the left of the equals sign is not a valid target for an assignment.
This error occurs because you meant to see if "a" equaled 3, but instead you told MATLAB to assign "a" a value of 3. You cannot do that on the same line that the if/while statement is on. The correct syntax is
>> if a == 3 >> end
This creates no errors (and you can put anything inside the conditional you want).
You cannot have a normal array with two different classes of data inside it. For example,
>> A = @(T) (1+T) A = @(T) (1+T) >> A(2) = 3 ??? Conversion to function_handle from double is not possible.
For such a purpose you should use cell arrays or struct arrays.
Here's the tricky one. Take a look at the following code:
>> A = [1,2,3;4,5,6;7,8,9]; >> A(2,:) = [3,5]; ??? Subscripted assignment dimension mismatch. >> A(2,:) = [1,4,5,6]; ??? Subscripted assignment dimension mismatch. >> A(1:2, 1:2) = [1,2,3,4]; ??? Subscripted assignment dimension mismatch.
What is happening here? In all three cases, take a look at the dimensions of the left and the right hand sides. In the first example, the left hand side is a 1x3 array but the right side is a 1x2 array. In the second, the left hand side is 1x3 while the right is 1x4. Finally, in the third, the left hand side is 2x2 while the right is 1x4. In all three cases, the dimensions do not match. They must match if you want to replace a specific portion of an existing variable. It doesn't matter if they have the same number of data points or not (as the third example shows); the dimensions must also be the same, with the exception that if you have a 1xn array on one side and an nx1 on the other MATLAB will automatically transpose and replace for you:
>> A(2,:) = [1;2;3] A = 1 2 3 1 2 3 7 8 9
If you do not want this be aware of it!
Struct array errors
Struct arrays are rather complex, and they have a rigid set of rules of what you can and can not do with them. Let us first deal with indexing within struct arrays. Suppose you define the variable "cube" and want to store the volume and the length of one side of two different cubes in a struct array. This can be done as follows:
>> cube(1).side = 1; >> cube(1).volume = 1; >> cube(2).side = 2; >> cube(2).volume = 8;
This seems like a good way of storing data and it is for some purposes. However, suppose you wanted to abstract the volumes from the struct and store them in one array. You cannot do it this way:
>> volumes = cube.volume ??? Illegal right hand side in assignment. Too many elements.
You'll notice that if you tell MATLAB to display cube.volume, it will display both values, but reassign the variable ans each time, because it is treated as two separate variables. In order to avoid the error, you must format 'cube.volume' as an array upon assignment.
>> volumes = {cube.volume}
You can also write in a separate assignment for each cube but this is more adaptable to larger numbers of cubes.
Just like extracting data, you must input the data one at a time, even if it is the same for all instances of the root (cube).
>> cube.volForm = @(S) (S^3) ??? Incorrect number of right hand side elements in dot name assignment. Missing [] around left hand side is a likely cause. >> cube(:).volForm = @(S) (S^3) ??? Insufficient outputs from right hand side to satisfy comma separated list expansion on left hand side. Missing [] are the most likely cause.
Unfortunately missing [] is not the cause, since adding them causes more errors. The cause is that you cannot assign the same value to all fields of the same name at once, you must do it one at a time, as in the following code:
>> for ii = 1:2 >> cube(ii).volForm = @(S) (S^3); >> end >> cube ans = 1x2 struct array with fields: volume side volForm
The same volume formula is then found in both cubes. This problem can be alleviated if you do not split the root, which is highly recommended. For example, you can use a struct like this:
>> shapes.cubeVol = @(S) (S^3); >> shapes.cube(1).vol = 1; >> shapes.cube(2).vol = 8;
This avoids having to use a loop to put in the formula common to all cubes.
Syntax errors
Parenthesis errors
Unlike in C++, you are not required to terminate every line with anything but a line break of some sort. However, there are still syntax rules you have to follow. In MATLAB you have to be especially careful with where you put your parenthesis so that MATLAB will do what you want it to.
A very common error is illustrated in the following:
>> A(1 ??? A(1  Error: Expression or statement is incorrectpossibly unbalanced (, {, or [.
This error is simple enough, it means you're missing a parenthesis, or you have too many. Another closely related error is the following:
>> A(1)) ??? A(1))  Error: Unbalanced or misused parentheses or brackets.
MATLAB tries to tell you where the missing parenthesis should go but it isn't always right. Thus for a complex expression you have to go through it very carefully to find your typo. A useful trick is to try to set a breakpoint a line after the offending line. It won't turn red until the error is corrected, so keep trying to correct it and saving the file until that breakpoint turns red. Of course, after this you have to make sure the parenthesis placement makes sense, otherwise you'll probably get another error related to invalid indecies or invalid function calls.
String errors
There are two ways that you can create a string; use the ' string ' syntax, or type two words separated by only whitespace (not including line breaks), as in
>> save file.txt variable
In this line, file.txt and variable are passed to the save function as strings. It is an occasional mistake to forget a parenthesis and accidentally try to pass a string to a function that does not accept strings as input:
>> eye 5 ??? Error using ==> eye Only input must be numeric or a valid numeric class name.
These should not be hard to spot because the string is colorcoded purple. Things like this occur if you uncomment a line of text and forget to change it.
Forgetting the closing ' in the other syntax for a string results in an obvious error:
>> A = 'hi ??? A = 'hi  Error: A MATLAB string constant is not terminated properly.
The unterminated string is colorcoded red to let you know that it is not terminated, since it's otherwise easy to forget.
A common mistake with strings is to try to compare them using the '==' operator. This does not work if the strings are not the same length, because strings are arrays of characters, and to compare arrays with '==' they must be the same size. To compare two strings you must use the strcmp function:
>> 'AA' == 'AaA' ??? Error using ==> eq Matrix dimensions must agree. >> strcmp('AA', 'AaA') ans = 0 >> strcmp('A', 'a') ans = 0 >> strcmp('AA', 'AA') ans = 1
Note that MATLAB strings are case sensitive, 'A' and 'a' are not the same string.
Also beware that the ' character for beginning and ending strings is the same character indicating transposition. So if you close a string and don't begin it, you will most likely end up with an error about an undefined variable (if you're trying to transpose an undefined variable) or just get really weird results because you transposed something you didn't intend to.
Other miscellaneous errors
You cannot leave trailing functions, and if you do MATLAB gives you an error that is similar but not exactly the same as that for a missing parenthesis, since it doesn't want to venture a guess:
>> A = 1+3+ ??? A = 1+3+  Error: Expression or statement is incomplete or incorrect.
These usually are not hard to spot, and often result from forgetting the "..." necessary to split a line.
The double colon is not the only "unexpected MATLAB operator", there is also "..", "....", and several other typos that generate this error.
If you accidentally type the ` character you get the error:
>> ??? `  Error: The input character is not valid in MATLAB statements or expressions.
This usually occurs because you intended to put a "1" in the equation but missed the key. Another possibility is that you named your mfile with unusual letters for computers. Like in Germany "ä, ü or ö". Be sure to name your mfiles only with usual letters and no capital letters.
Function Calling errors
It is quite possible to try to call a function that doesn't exist, such as:
>> samplemat = [1 2; 1 4] >> A = eigen(samplemat); ??? Undefined command/function 'eigen'.
This can happen because you do not know the name of the function that performs the operation intended (for example, if you wanted to compute the eigenvalues of matrix "samplemat", you would want to call eig, not eigen). It is often useful to pull up MATLAB's help (go to help > product help or type doc into the command prompt) and do a search for the operation you want.
If you're trying to call a function you created and you get this error, there are several possible reasons:
 The mfile must be in one of the paths listed under file > set path, or must be in your current directory
 The mfile must have the same name as the name in the function declaration. You must be aware of this especially if you change the name of your functions, you must also change the name of the file or MATLAB will not find the right function!
If MATLAB finds the function, it will attempt to run it. However, there are several potential pitfalls to avoid in calling functions. It is necessary to know the nature of the input and output arguments of a given function in order to call it. For MATLAB's builtin functions, this information is found in the documentation, or by typing
>> help functionname
It is a good idea to set up some comments so that the help function can read them in your own code as well, so you can keep track of how all your functions work and what they do at a quick reference. To do this, note that the help function reads only the block of comments directly under the function declaration, so for example, if you write a function like this:
function outvars = myfunc(invars) % function outvars = myfunc(invars) % Outputs outvars % All of this is outputted when you type >> help myfunc
% But this wouldn't be
save the function as "myfunc.m", and type
>> help myfunc
it will output:
>> function outvars = myfunc(invars) Outputs outvars All of this is outputted when you type >> help myfunc
Most functions (not all however) require at least one input argument, and calling it with too few will result in an error:
>> A = ode45() ??? Error using ==> ode45 Not enough input arguments. See ODE45.
You cannot call a function with too many input arguments either:
>> A = plus(1,2,3) ??? Error using ==> plus Too many input arguments.
Input arguments must be in a format expected by the function. This will be very functionspecific, so see the documentation or help for details on what they expect. For example, the first argument to ODE45 and other ODE solvers has to be the function handle; if you pass arguments in the wrong order you will be given an error to that effect.
You can choose how many of the output arguments you want out of those available by using the bracket notation. You can choose to save fewer outputs than the function offers, but you cannot assign more variables than the function can output:
>> A = [1,2;3,4] D = eig(A); %one output argument [V,D] = eig(A); %two output arguments [V,D,Mistake] = eig(A); ??? Error using ==> eig Too many output arguments.
All assigned output arguments must also be of the correct class if you are replacing parts of an array that already exists (see the section on assignment for more on this). If you're creating a new variable with the output, this is not an issue.
Control Flow errors
The most common one by far is if you forget the 'END', which is an issue in Mfile functions. It will tell you that 'at least one END is missing' and try to tell you where the loop or conditional statement starts.
If you have too many END statements and more than one function in an Mfile, MATLAB may give you a cryptic message about not formatting the functions correctly. This is because all functions in the same Mfile must either end with an END statement or not. It doesn't matter which, but if you have too many END statements in one of the functions, MATLAB will think your function is ending early and will get confused when the next function in line does not have an END statement at the end of it. So if you get this confusing message, look for extra END statements and it should fix your problem. If the message is displayed when publishing, say to an HTML file, the problem may be an erratic hierarchical indentation. Try selecting all and then hitting cntrli for automatic indentation to fix the problem.
Having an extra END in a 'switch' statement gives a message that you used the 'case' keyword illegally, because MATLAB thinks you ended the switch statement early, and 'case' has no meaning outside a 'switch' statement.
Other errors
There are numerous types of errors that do not generate errors from the MATLAB compiler, which have to do with calling the wrong function, using the wrong operation, using the wrong variable, introducing an infinite loop, and so on. These will be the hardest to fix, but with the help of the MATLAB debugger, they will be easier to find. See Debugging M Files for details on how to use the debugger.
Detecting or planning an error
No matter how accurate the programming is, errors might happen. Using debug techniques are to great help, but planning an error or expecting an error could prove to be just as valuable. This includes making a possibly unneeded if block to decide what to do. I.e. if x < 5 do this and x > 5 do something else. Also inside the big loops add an if block with modulo, like: if not ( mod ( ii , 5 ) ) % do something; end. Now the loop only does a test for every ii counter which can be divided by 5 without any remainder after the division. Some syntax errors or logical errors inside a loop happens after looping for a long time, if an error happens then the error message is displayed, explaining where it happened but not necessarily why it happened. I.e. vector x is one element shorter than element y, and x .* y could not happen. This mistake often happens on the last element in the shortest vector, and is quite difficult to discover unless measures are taken. try % do something; catch me me.getReport; then a breakpoint and even disp(me.getReport) will help in this situation. If the error is not fatal the code may even continue, but instead displaying the error as a message or it could be converted to a warning.
Included Matlab tools / functions: warning, lastwarn, disp, try catch, dbstack, rethrow, throwAsCaller and Matlab help on the above functions to discover pros and cons for each method.
 In MATlab 6.x (not sure exactly which builds this problem occurs in) the random number generator will generate the same sequence the first time you execute the command.
 In all versions, when operating on a network, do not edit the same file under two different paths, e.g. a mapped drive path and a UNC path (Y:\myfile.m and \\server\folder\myfile.m). You may experience strange behavior (e.g. breakpoints stop working) or other issues depending on which path MATLAB takes to execute the script vs which path it uses for the breakpoints. This same caveat most likely applies to Linux and Windows hard links under different names. Obvious, and bad practice, but hard to find if you have many files opened in the editor and happen to be accessing files using both modes.
This section explains things you can do if you fix all the syntax errors (the ones that give you actual error messages), the program runs... but it gives you some result you don't want. Maybe it goes into an infinite loop, maybe it goe through the loop one too few or one too many times, maybe one of your "if" statements doesn't work, maybe the program is giving you "infinity" or "NaN" as an answer (which usually isn't very useful!)... there's as many things that can go wrong as there are lines in the code. Thankfully there are techniques for both fixing and improving on working MATLAB code.
Using MATLAB's Debugging tool
Using the Debugging Tool will let you stop your program in midexecution to examine the contents of variables and other things which can help you find mistakes in your program.
Mfile programs are stopped at "breakpoints". To create a breakpoint, simply press F12 and a red dot will appear next to the line where your cursor is. You can also click on the dash next to the line number on the left side of the Mfile window to achieve the same result.
Then press F5 or Debug>Run from the menu to run the program. It will stop at the breakpoint with a green arrow next to it. You can then examine the contents of variables in the workspace, step, continue or stop your program using the Debug menu. To examine contents of a variable, simply type its name into the workspace, but be warned: you can only look at the values of variables in the file you stop in, so this means that you'll probably need multiple breakpoints to find the source of your problem.
There are several different ways you can move through the program from a breakpoint. One way is to go through the whole program, line by line, entering every function that is called. This is effective if you don't know where the problem is, but since it enters every function (including MATLAB functions like ode45), you may not desire to use it all the time. Thankfully, there's also a way to simply step through the function you're currently stopped in, one line at a time, and instead of going through the child functions line by line MATLAB will simply give you the results of those functions.
Finally, note that you cannot set a breakpoint until you save the Mfile. If you change something, you must save before the breakpoint "notices" your changes. This situation is depicted in MATLAB by changing the dots from red to gray. Sometimes, you'll save but the dots will still be gray; this occurs when you have more than one breakpoint in multiple files. To get around this (which is really annoying), you have to keep going to "exit debug mode" until it turns gray. Once you're completely out of debug mode, your file will save and you'll be ready to start another round of debugging.
Using comments to help you debug code
If you want to test the effects of leaving out certain lines of code (to see, for example, if the program still returns Inf if you take them out), you can comment out the code. To do this, highlight it and then go to:
Text > Comment
Or press CTRL+R. This will simply put a '%' in front of every line; if the line is already commented out it will put another '%' there so when you uncomment them the pattern of comment lines will not change. Commented lines will be ignored by the compiler, so the effect will be that the program is run without them.
To uncomment a line go to
Text > Uncomment
Or press CTRL+T.
Another use of commenting is to test the difference between two different possible sets of code to do something (for example, you may want to test the effect of using ODE113 as opposed to ODE45 to solve a differential equation, so you'd have one line calling each). You can test the difference by commenting one out and running the program, then uncommenting that one and commenting the other one out, and calling the program again.
How to escape infinite loops
If your program is doing nothing for a long time, it may just be slow (MATLAB creates a lot of overhead and if you don't use arrays wisely it will go very, very slow) but if you are testing a small module, it is more likely that you have an infinite loop. Though MATLAB can't directly tell you you have an infinite loop, it does attempt to give you some hints. The first comes when you terminate the program. Terminate it by pressing CTRL+C and MATLAB will give you a message telling you exactly what line you stopped on. If your program is running a long time, it is likely the line you stopped in is in the middle of an infinite loop (though be warned, if the loop calls a subfunction, it is likely that you will stop in the subfunction and not the parent. Nevertheless, MATLAB also will tell you the lines of the parents too so you can track down the loop easily enough).
However, sometimes MATLAB won't even let you return to the main window to press CTRLC. In this case you probably have to kill the whole MATLAB process. After this, add a "pause (0.001)" or a similarly small value in the loop you suspect to be the infinite one. Whenever MATLAB passes this instruction you will be able to interact with MATLAB for a (very) short time, e.g. go to the main window and press CTRLC with MATLAB being able to respond to your command.
Other debugging tips
When inside a function, a loop or just anywhere in the script use a special comment syntax. The %% is the Cellmode commenting. By adding a %% on the line above the interesting code and another %% below the code a cell is created. Now this cell may be executed and modified in memory without the requirement to save the code, script or function. By adding some text after the %% a heading for this cell section is created. I.e. %% Start debugging infinite loop
Another method is to enter the breakpoint, selecting the interesting part and copy this to a new file. Now the code may be changed within this new file and tested. When the modified code is working as expected the debug session may be ended. The code from the temporary file may be copied back and replace the debugged code. This method lets the user run this code snippet multiple times include the %% if the code should be run in cell mode.
Instead of using the IDE to run the code, debug the code or selecting breakpoints, command line functions may be used. Just enter db and press the TABkey to choose the functions. The functions dbstatus and dbstack are two usable functions. Experiment with the functions and use help functon name or select the function name and press the F1key
The last debugging tips in is to add possible code inside the comments I.e. % plot(x,y); % This debug plot function plots the value vector y with input x Now select the plot(x,y) with or without the ; and press F9 (run the selected code). Use help and preferences to find and modify keyboard shortcuts if needed. CTRL+D on the selected y variable opens it inside the variable editor, not to forget hovering the mouse over any variable will display it contents if possible. Even the plot command itself is a great debugging tool, when it comes to visualize the variables.
The final tips is actually a summary. Experiment with the above methods and even combine them such that the debugged code is both run efficiently, has valuable comments and have means to be debugged if necessary. Make plans for coding mistakes by adding comments and helper functions. Make small functions which does what it is designed to do, then implement this function in the complete program or script. Inside the functions use try, catch me and me.getReport; And if there are recurring mistakes, expect them to happen and program accordingly. Infinite loops are very common mistakes so by adding functionality to discover this mistake is a great time saver. Another tips could be unit testing.
Chapter 6: Mathematical Manipulations
Linear Algebra
Operations
Squaring a matrix
a=[1 2;3 4];
a^2;
a^2 is the equivalent of a*a. To square each element:
a.^2
The period before the operator tells MATLAB to perform the operation element by element.
Determinant
Getting the determinant of a matrix, requires that you first define your matrix, then run the function "det()" on that matrix, as follows:
a = [1 2; 3 4];
det(a)
ans = 2
Symbolic Determinant
You can get the symbolic version of the determinant matrix by declaring the values within the matrix as symbolic as follows:
m00 = sym('m00'); m01 = sym('m01'); m10 = sym('m10'); m11 = sym('m11');
or
syms m00 m01 m10 m11;
Then construct your matrix out of the symbolic values:
m = [m00 m01; m10 m11];
Now ask for the determinant:
det(m)
ans = m00*m11m01*m10
Transpose
To find the transpose of a matrix all you do is place an apostrophe after the bracket. Transpose switch the rows and columns of a matrix.
Example:
a=[1 2 3]
aTranspose=[1 2 3]'
or
b=a' %this will make b the transpose of a
when a is complex, the apostrophe means transpose and conjugate.
Example
a=[1 2i;3i 4];
a'=[1 3i;2i 4];
For a pure transpose, use .' instead of apostrophe.
Systems of linear equations
There are lots of ways to solve these equations.
Homogeneous Solutions
Particular Solutions
State Space Equations
Special Matrices
Often in MATLAB it is necessary to use different types of unique matrices to solve problems.
Identity matrix
To create an identity matrix (ones along the diagonal and zeroes elsewhere) use the MATLAB command "eye":
>>a = eye(4,3) a = 1 0 0 0 1 0 0 0 1 0 0 0
Ones Matrix
To create a matrix of all ones use the MATLAB command "ones"
a=ones(4,3)
Produces:
a = 1 1 1 1 1 1 1 1 1 1 1 1
Zero matrix
The "zeros" function produces an array of zeros of a given size. For example,
a=zeros(5,3)
Produces:
a = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
This type of matrix, like the ones matrix, is often useful as a "background", on which to place other values, so that all values in the matrix except for those at certain indices are zero.
Row reduced echelon form
To find the Row reduced echelon form of a matrix just use the MATLAB command rref
Example:
a=[1 2 3; 4 5 6]; b=rref(a);
It's that simple. (I believe that MATLAB uses the GaussJordan elimination method to make this computation; don't quote me on that (I'm not even sure if there are other methods)).
Inverse
To find the inverse of a matrix use the MATLAB command inv. (note that the matrix must be square)
Example:
a=[1 2 3;4 5 6;7 8 9]; b=inv(a);
Cofactor, minor
The Jacobian
t=jacobian(e,w);
e is a scalar vector, w is a vector of functions. Also, this does not solve equations symbolically unless you define the w vector functions as symbolics prior to executing this statement.
Example:
syms x y z; w=[x y z]; e=[1 2 3]; t=jacobian(e,w);
Differential Equations
Differential equation solver syntax
All of the differential equations have the same syntax that you must use, and the same input and output arguments. All of the solvers require three input arguments: a function handle to the differential equation you want to solve, a time interval over which to integrate, and a set of initial conditions. Let us suppose we want to solve the simple differential equation y' = y, y(0) = 1, which has the true solution y(t) = e^t. Suppose we want the solution between t = 0 and t = 1.
To use function handles, you must first create an Mfile with the function in it like so:
function Yprime = func(t, y) Yprime = 0; Yprime = y;
Note that you must include the time argument even if it is not used in the differential equation. The initialization of Yprime to an array of zeros will save you grief if you try to solve more than one function; Yprime must be returned as a VERTICAL array but, if you don't initialize it as a verical array (or transpose at the end), it will return a HORIZONTAL array by default.
Also note that, with the exception of ode15i, the function must be solved explicitly for y'.
Once this file is created, call the ODE function with the arguments in the order (function, timeinterval, initialcond):
>> ode45(@func, [0,1], 1)
The other method is to use anonymous functions, which is only useful if you have one function (otherwise you must use function handles). You again must declare the anonymous function in terms of both the dependent variable(s) and time:
>> func = @(t,y) y; >> ode45(func, [0,1], 1)
Calling the ODE function without input arguments gives a graph of the solution. Calling it with one output argument returns a struct array:
>> Struct = ode45(func, [0,1], 1) Struct = solver: 'ode45' extdata: [1x1 struct] x: [1x11 double] y: [1x11 double] stats: [1x1 struct] idata: [1x1 struct]
This data is mostly used to, in the future, call the 'deval' function to get the answer at any time you want:
>> Solution = deval(Struct, 0.5) Solution = 1.6487
Deval can also return the derivative at the point of interest by including a second output argument.
>> [Solution, Derivative] = deval(Struct, 0.5) Solution = 1.6487 Derivative = 1.6487
Since the derivative of e^x is itself it makes sense that the derivative and solution are the same here.
Calling ode45 with two output arguments returns two lists of data; t first, then the independent variables in an appropriatelysized matrix.
ODE Options
The are a rather large number of options that MATLAB gives you to modify how it solves the differential equations. The help file does a pretty good job describing all of them so they won't be described in detail here. To get a list use the help function:
>>help odeset
To get a list of the different options' names and what you have to pass to it, just type 'odeset' into the command prompt. It returns either a data type or a finite list of options. It also lists, in parenthesis, the default values of all the options.
To set a specific option or list of options, type the name of the option first and then the value of the option you want. For example, suppose you want to tighten the default relative tolerance from 10^3 to 10^4. You would call 'odeset' as follows:
>> option = odeset('RelTol', 10^4);
Note that the option name must be passed as a string, or else you'll get an 'undefined variable' error most likely. More than one option can be passed at a time by just putting them all in a list:
>> option = odeset('RelTol', 10^4, 'AbsTol', 10^7, 'MassSingular', 'no');
The options structure can then be passed to the ode function as a forth (optional) input argument:
>> [T,X] = ode45(@func, [0,1], 1, option);
This will return more accurate values than default because the error tolerances are tighter. It should also compute faster because MATLAB is not checking to see if this is a differentialalgebraic equation (this is what the MassSinglular option does; it is usually set to 'maybe' so MATLAB checks by itself).
The ODE solvers
MATLAB doesn't just have one ODE solver, it has eight as of the MATLAB 7.1 release. Some are more suited for certain problems than others, which is why all of them are included. The MATLAB help has a list of what functions each one can do, but here is a quick summary, in roughly the order you should try them unless you already know the classification of the problem:
 Most problems can be solved using ode45, and since this is the best tradeoff of speed and accuracy it should be the first one you use.
 If you need a really tight error tolerance or a lot of data points, use ode113.
 If you have a relatively loose error tolerance or the problem is slow with ode45, try ode23.
 If the problem is truly stiff and ode45 fails, use ode23tb for loose tolerances, ode23s for slightly tighter tolerances with a constant mass matrix, or ode15s for tighter tolerances or nonconstant mass matrices.
 If you need a solution without numerical damping on a stiff problem, use ode23t.
 The s indicates that the algorithm is intended for stiff problems.
 There is one other ODE solver, which is special:
 Implicit problems can only be solved using ode15i.
Since ode15i has some differences in its syntax, it is discussed next.
Implicit ODEs: ODE15i
Since ode15i is the only ODE solver that solves implicit equations, it must have some special syntactical rules on how to input the function.
If you are using ode15i declare the function as follows:
function Z = func(t,y,Yprime) Z = 0; Z = y  Yprime;
Note that with ode15i, you must put the function into normal form (solve it for 0), whereas for all other ODE functions you must solve explicitly for y'. Also notice that you must declare three input arguments instead of the usual two.
When you call ode15i, you must not only include initial conditions for y but also for Yprime. The initial conditions for Yprime go into the fourth argument:
>> [t,x] = ode15i(@func, [0,1], 1, 1);
This will return similar results to ode45 when used for the explicit equation, but has fewer data points.
The options structure is passed to ode15i as the optional fifth argument. All output options from ode15i are the same as for the other ODE solvers. c=3
d=0.002
m=(1/d*log(2))^(1/c)
Chapter 7: More advanced I/O
Now that we've covered basic file input output (I'll get into more detailed file manipulation later) we can move on to the next step.
In the section Basic Reading and Writing data we already had the data in the form of a spreadsheet. How did it get to that spreadsheet and how do we send it some where else? This question will attempt to be answered in the following section. There are many ways to transmit and receive data. I've even heard of this newfangled thing called the easternet or internet or whatever, but for now we will assume we are in a University lab with no Internet connection (don't laugh I've been in this situation more times than I like to remember). In this case, we will use the computer's serial port, which implements the RS232 physical layer protocol. Although this protocol is very slow (usually no more than 9600 bits/s), it's very simple to implement and thus it's used widely on embedded devices.
MATLAB provides us with there style of reading and writing to the serial port.
 You must create a serial port object.
object=serial(port,'Property name',propertyValue);
Example: I will now create a serial object called serialOne
serialOne=serial('COM1', 'BaudRate', 9600);
(for those of you more familiar with C this should look very similar to creating a handle: In fact it is the MATLAB way of making handles)
Most computers call the serial ports COM and then some number usually 14 (depending on how many there are). This also includes DB9, DB25 and other various DB type connectors.
2. Now that the computer knows there is a serial port object you have to tell it to open
 the object. Use the fopen command
3. Write to the port
4. Close object.
Example:
serialOne=serial('COM1', 'BaudRate', 9600); fopen(serialOne); fprintf(serialOne,'textFile.txt'); fclose(serialOne);
further reading
The USB port is a type of serial port. It is, after all, the Universal SERIAL Bus. I wrote that twice because all of the books I have read on USB seem to muddle that quite a bit. There are some minor and major differences to how you use the USB ports but the idea is very much the same. I did this a while back and have to reread some stuff. (I also plan to either start a wiki book about USB or join one that is already started I have to look into this more).
further reading
Chapter 8: Examples
Filtering is a broad subject. For the MATlab wiki I will focus on how to implement filters. For more on the theory of filtering the reader should reference the Digital Signal Processing wiki book.
The Moving Average Filter
Formula:
MATLAB implementation(All the code here was intended to be put in an Mfile):
clc;
clear; % clear all
v=.01
f=100;
fs=5000;
t=0:1/fs:.03
x=sin(2*pi*f*t); %original signal
r=sqrt(v)*randn(1,length(t)); %noise
Xw=x+r; %signal plus noise (filter input)
% I have chosen h=3
for n=3:length(Xw),
y(n)=sum(Xw(n2:n))/3; %y[n] is the filtered signal
end
plot(y);
hold;
plot(x,'r'); %plot the original signal over top the
%filtered signal to see the difference
The moving average filter is simple and effective. One of the things that is a problem is the lag associated with the moving average filter. The more samples used the longer the lag experienced(All filters have lag). How much lag can be tolerated is up to the individual.
The Alpha Beta filter
The Kalman Filter
The Kalman filter is a recursive method of combining two estimates to determine the truth. A few parameters that are widely used are the initial conditions or current value and measured data.
Equation:
Example:
n=100;
sigma=(20/6076);
R=100;
Rm=R+sigma*randn;
Rs(1)=Rm(1);
Cs=sigma^2
for i=2:n
Rm(i)=R+sigma*randn;
alpha=Cs/(Cs+sigma^2);
Rs(i)=Rs(i1)+alpha*(Rm(i)Rs(i1));
Cs=(1alpha)*Cs;
end
All this code does is take a constant value R and adds noise to it. Then it filters the new signal in an effort to separate the noise from the original signal.
The discrete Fourier transform
What is it?  DFT element  matlab example and comments  

How often do you want to sample?  sampling frequency 
 
For how long do you want to sample?  time range 
 
How many samples does that give you? 
 
How far apart are each of the frequencydomain result points? 
 
What signal do you want to sample?  input 
 
What are the results?  Fourier transform  fft_x=fft(x, length(x));  
What frequencies does the signal have?  fft_x_mag=abs(fft_x);  
What phase relationships?  fft_x_phase=unwrap(angle(fft_x));  
How do you view the results? 
 
What about the power spectrum? 

References
Lyons, Richard G. Understanding digital signal processing. Upper Saddle River: Prentice Hall PTR, 2001. ISBN 0201634678. Chapter 3 discusses the DFT.
Introduction
I think that is is important to note here how concepts are implemented. Control systems in MATlab will use both the numeric methods and programming methods to achieve the design criteria. This article is not meant to teach the theory of controls.
See also: Control Systems
Chapter 9: ObjectOriented Programming
A struct as defined and used in Octave
A structure in Octave groups different data types called fields in a single object. Fields are accessed by their names.
Declaring a structure
A structure is declared by assigning values to its fields. A period (.) separates the name of the field and the name of the structure:
>> city.name = 'Liege';
>> city.country = 'Belgium';
>> city.longitude = 50.6333;
>> city.latitude = 5.5666;
The fields of a structure and their values can be displayed by simply entering the name of the struct:
>> city city = { name = Liege country = Belgium longitude = 50.633 latitude = 5.5666 }
Manipulating structures
A structure can be copied as any objects:
>> city_copy = city;
In most circumstance, the fields of a structure can be manipulated with the period operator. The value of a field can be overwritten by:
>> city.name = 'Outremeuse';
In the same way, the value of a field can be retrieved by:
>> city.name
ans = Outremeuse
The function isstruct can be used to test if object is a structure or not. With the function fieldnames all field names are returned as a cell array:
>> fieldnames(city) ans = { [1,1] = name [2,1] = country [3,1] = longitude [4,1] = latitude }
To test if a structure contains the a given field named, the function isfield can be used:
>> isfield(city,'name') ans = 1
The value of a field can be extract with getfield:
>> getfield(city,'name')
ans = Liege
or using
>> city.('name') ans = Liege
In a similar way, the value of a field can be set with setfield:
>> setfield(city,'name','Outremeuse')
The functions isfield, getfield and setfield are useful when the names of a structure are determined during execution of the program.
You can remove a field of a struct array with the rmfield function.
>> city = rmfield(city, 'name');
would remove the 'name' field from the city struct and copy the result back onto the original structure. MATlab stores methods (separate Mfile) in class directories not on the standard search path. The two minimum things needed in order to create a class are the constructor and display Mfiles.
Chapter 10: Comparing Octave and MATLAB
This page was transwikied from another project and needs to be bookified. This page either needs to be altered to become the main page of a book, or altered to fit the "local manual of style" of the book it is to be included in. Please remove {{bookify}} after the page is bookified. 
Octave is a free computer program for performing numerical computations (created as part of the GNU project) which is mostly compatible with MATLAB.
History
The project was conceived around 1988. At first it was intended to be a companion to a chemical reactor design course. Real development was started by John W. Eaton in 1992. The first alpha release dates back to January 4, 1993 and on February 17, 1994 version 1.0 was released.
The name has nothing to do with music. It was the name of a former professor of one of the authors of Octave who was known for his ability to quickly come up with good approximations to numerical problems.
Technical details
 Octave is written in C++ using STL libraries.
 Octave has an interpreter that interprets the Octave language.
 Octave itself is extensible using dynamically loadable modules.
 Octave interpreter works in tandem with gnuplot and Grace software to create plots, graphs, and charts, and to save or print them.
Octave, the language
The Octave language is an interpreted programming language. It is a structured programming language (an example of which is the C language) and supports many common C standard library constructs, and can be extended to support UNIX system calls and functions. However, it does not support passing arguments by reference.
Octave programs consist of a list of function calls or script. The language is matrixbased and provides various functions for matrix operation. It is not objectoriented, but supports data structures.
Its syntax is very similar to MATLAB, and carefully programming a script will allow it to run on both Octave and MATLAB.
Because Octave is made available under the GNU General Public License, it may be freely copied and used. The program runs under most Unix and Unixlike operating systems, as well as Microsoft Windows.
Notable features
 Command and variable name completion
Typing a TAB character on the command line causes Octave to attempt to complete variable, function, and file names. Octave uses the text before the cursor as the initial portion of the name to complete.
 Command history
When running interactively, Octave saves the commands typed in an internal buffer so that they can be recalled and edited.
 Data structures
Octave includes a limited amount of support for organizing data in structures. For instance:
octave:1> x.a = 1; x.b = [1, 2; 3, 4]; x.c = "string"; octave:2> x.a x.a = 1 octave:3> x.b x.b = 1 2 3 4 octave:4> x.c x.c = string
 Shortcircuit boolean operators
Octave's `&&' and `' logical operators are evaluated in a shortcircuit fashion (like the corresponding operators in the C language) and work differently than the element by element operators `&' and `'.
 Increment and decrement operators
Octave includes the Clike increment and decrement operators `++' and `' in both their prefix and postfix forms.
 Unwindprotect
Octave supports a limited form of exception handling modelled after the unwindprotect form of Lisp. The general form of an unwind_protect block looks like this:
unwind_protect body unwind_protect_cleanup cleanup end_unwind_protect
 Variablelength argument lists
Octave has a real mechanism for handling functions that take an unspecified number of arguments without explicit upper limit.
Here is an example of a function that uses the new syntax to print a header followed by an unspecified number of values:
function foo (heading, ...) disp (heading); va_start (); while (nargin) disp (va_arg ()); endwhile endfunction
 Variablelength return lists
Octave also has a real mechanism for handling functions that return an unspecified number of values. For example:
function [...] = foo (n) for i = 1:n vr_val (i); endfor endfunction
See also
References
Octave has been mainly built with MATLAB compatibility in mind. It has a lot of features in common with MATLAB:
 Matrices as fundamental data type.
 Builtin support for complex numbers.
 Powerful builtin math functions and extensive function libraries.
 Extensibility in the form of userdefined functions.
Some of the differences that do exist between Octave and MATLAB can be worked around using "user preference variables."
GNU Octave is mostly compatible with MATLAB. However, Octave's parser allows some (often very useful) syntax that MATLAB's does not, so programs written for Octave might not run in MATLAB. For example, Octave supports the use of both single and double quotes, whereas older versions of MATLAB only supported only single quotes, which meant parsing errors occurred if you tried to use double quotes (e.g. in an Octave script when run on MATLAB). More recent versions of MATLAB introduced double quotes, but with different functionality to single quotes (albeit with some overlap in functionality). Octave and MATLAB users who must collaborate with each other need to take note of these issues and program accordingly.
 Note: Octave can be run in "traditional mode" (by including the traditional flag when starting Octave) which makes it give an error when certain Octaveonly syntax is used.
This chapter documents instances where MATLAB's parser will fail to run code that will run in Octave, and instances where Octave's parser will fail to run code that will run in MATLAB. This page also contains notes on differences between things that are different between Octave (in traditional mode) and MATLAB.
CStyle Autoincrement and Assignment operators
Octave supports Cstyle autoincrement and assignment operators:
i++; ++i; i+=1; etc.
MatLab does not.
Product of booleans
MATLAB (R2011b) and Octave (3.6.4) responds differently when computing the product of boolean values:
X = ones(2,2) ; prod(size(X)==1) MATLAB: PROD is only supported for floating point input. Octave: ans = 0
They both produce the same result (ans=0) in MATLAB (R2015a) and above
nargin
Nargin returns the number of input arguments of a function. MATLAB (R2011b) will not allow the following; Octave will.
function myfun = testfun(c)
if (nargin == 1)
nargin = 2;
else
nargin = 3
end
startup.m
MATLAB will execute a file named 'startup.m' in the directory it was called from on the command line. Old versions of Octave do not. Starting with Octave 4.2.0 it behaves the same as Matlab. For older versions of Octave, it will execute a file named '.octaverc' which can be edited to execute existing startup files. This means that '.octaverc' can be edited to look for and execute a 'startup.m' file.
if ( exist ('startup.m', 'file') )
source ('startup.m') # load startup.m like MATLAB
endif
['abc ';'abc']
['abc ';'abc'] is allowed in Octave; MATLAB returns: ?? Error using ==> vertcat
In Octave the result will be a 2 by 3 matrix.
Calling Shells
the "! STRING" syntax calls a shell with command STRING in MATLAB. Octave does not recognize ! as system call, since it is used in logical operations. Always use 'system (STRING)' for compatibility.
If you really miss the onecharacter shortcut, for convenience on the command line you can create a similar shortcut by defining the following in your '.octaverc' file:
function S(a), system(a); end
Now "S STRING" will evaluate the string in the shell.
Attempting to load empty files
MATLAB lets you load empty files, OCTAVE does not.
system('touch emptyfile'); A = load('emptyfile')
MATLAB R2011b : A=[] Octave 4.2.0 : error: load: unable to determine file format of 'emptyfile'
fprintf and printf
Octave supports both printf
and fprintf
as a command for printing to the screen. MATLAB requires fprintf
:
foo = 5; printf ('My result is: %d\n', foo) % Prints to STDOUT. Octave only
fprintf
covers writing both to the screen and to a file by omitting the optional filehandle argument:
foo = 5; fprintf('My result is: %d\n', foo) % Prints to STDOUT. Octave and MATLAB
Whitespace
MATLAB does not allow whitespace before the transpose operator but Octave does (it is just an operator like others).
[0 1]' % works in MATLAB and Octave [0 1] ' % works only in Octave
Line continuation
MATLAB always requires ...
for line continuation.
rand (1, ... 2)
while Octave also supports
rand (1, 2)
For both programs, a line break without '...' within an array shifts to the next row
>> R=[1 2 3 7 8 9]
R = 1 2 3 7 8 9
Assignment
Octave supports
z = y = x + 3
MATLAB requires
y = x + 3 z = y
Logical operator NOT
Octave allows users to use both ~ and ! with boolean values. The first is for MATLAB compatibility, while ! will be more familiar to C/Java/etc programmers. If you use the latter, however, you'll be writing code that MATLAB will not accept:
 For notequal comparison, Octave can use both '~=' or '!='. MATLAB requires '~='.
GNU Octave Control Package
Both MATLAB and Octave have toolboxes intended to control system design. In Octave, the toolbox is called the Octave Control Package. The package can be downloaded, compiled and installed with the command pkg install control
from the Octave prompt. Users of Debian and its derivatives can install it by installing the package "octavecontrol", if it is not installed by default.
For more information about functions' syntax, type help <name of function>. For more information about the Control Package, view the PDF manual in the package's "doc" folder.
Small differences exist  an example is c2d. Here are the two formats for the bilinear transformation with an analog model C:
* discrete = c2d(C,0.5,'tustin'); % Matlab
* discrete = c2d(C,0.5,'bi'); % GNU Octave
Some other differences
 MATLAB uses the percent sign '%' to begin a comment. Octave uses both the hash symbol
#
and the percent sign%
interchangeably.  For exponentiation, Octave can use
^
or**
; MATLAB requires^
.  For string delimiters, Octave can use
'
or"
; old versions of MATLAB required'
; current versions of MATLAB can use'
or"
, but with different (slightly overlapping) functionality.  To end blocks, Octave can use
end
or specify the block withendif, endfor, ...
; MATLAB requiresend
.  Octave supports Cstyle hexadecimal notation (e.g. "0xF0"); MATLAB requires the
hex2dec
function (e.g. "hex2dec('F0')").  If something (like Netlab) needs a function named fcnchk, create a file named fcnchk.m with the contents shown below and put it where Octave can find it:
function f=fcnchk(x, n)
f = x;
end
 The main difference used to be the lack of GUI for Octave. With version 4.0 Octave has a GUI as its default interface.
Notes about specific functions
 For "dbstep, in" use "dbstep"; for "dbstep", use "dbnext"
 For "eig(A,B)" use "qz(A,B)"
 fputs function is not available in MATLAB. Use fprintf instead.
 strftime function is not available in MATLAB. Use datestr instead.
 time function is not available in MATLAB. Use now instead.
 As of 4.2.1, Octave does not print outputs to the console until it has completed all waiting commands, unlike MATLAB. This behavior is controlled by the boolean variable
page_output_immediately
(default:0
), and it is not ameliorated intraditional
.  strread and textscan in Octave 3.4.0 are not fully compatible with their implementations in MATLAB 2009b (and probably later versions as well). For instance, the N=1 option (repeat reading format until end of string) is not implemented in Octave 3.4.0 . Using a value of N=a positive integer (read format N times) does work the same as in MATLAB.
 textscan function is not included in Octave versions prior to 3.4.0. Use fscanf instead.
 For the linprog function, MATLAB is more permissive by allowing the "a" and "b" inputs to be either row or column vectors. Octave requires that they be column vectors.
 In Octave, one can specify data labels (or legends) with the plot function, while in MATLAB, one can only use the legend function.
Octave: plot(x, y, ';label;') MATLAB/Octave: plot(x, y); legend('label')
 The error(msg) function in MATLAB is a noop if the message is empty. In Octave, it results in an error.
References
See also
Chapter 11: Toolboxes
Introduction to the Symbolic Math Toolbox
The symbolic toolbox is a bit difficult to use but it is of great utility in applications in which symbolic expressions are necessary for reasons of accuracy in calculations. The toolbox simply calls the MAPLE kernel with whatever symbolic expressions you have declared, and then returns a (usually symbolic) expression back to MATLAB. It is important to remember that MAPLE is not a numeric engine, which means that there are certain things it doesn't let you do that MATLAB can do. Rather, it is useful as a supplement to provide functions which MATLAB, as a numerical engine, has difficulty with.
The symbolic math toolbox takes some time to initialize, so if nothing happens for a few seconds after you declare your first symbolic variable of the session, it doesn't mean you did anything wrong.
The MATLAB student version comes with a copy of the symbolic math toolbox.
Symbolic Variables
You can declare a single symbolic variable using the 'sym' function as follows.
>> a = sym('a1') a = a1
You can create arrays of symbolic expressions like everything else:
>> a1 = sym('a1'); >> a2 = sym('a2'); >> a = [a1, a2] a = [ a1, a2]
Symbolic variables can also be declared many at a time using the 'syms' function. By default, the symbolic variables created have the same names as the arguments of the 'syms' function. The following creates three symbolic variables, a b and c.
>> syms a b c >> a a = a
Symbolic Numbers
Symbolic numbers allow exact representations of fractions, intended to help avoid rounding errors and representation errors. This section helps explain how to declare them.
If you try to add a number into a symbolic array it will automatically turn it into a symbolic number.
>> syms a1, a2; >> a = [a1, a2]; >> a(3) = 1; %would normally be class 'double' >> class(a(3)) ans = sym
Symbolic numbers can also be declared using the syntax a(3) = sym('number'). The difference between symbolic numbers and normal MATLAB numbers is that, if possible, MAPLE will keep the symbolic number as a fraction, which is an exact representation of the answer. For example, to represent the number 0.5 as a fraction, you can use:
>> sym(0.5) ans = 1/2
Here, of course, MATLAB would normally return 0.5. To make MATLAB change this back into a 'double', type:
>> double(ans) ans = 0.5000
Other class conversions are possible as well; for instance, to change it into a string use the 'char' function. There is no function to directly change a symbolic variable into a function handle, unfortunately.
A caveat: Making a symbolic variable of negative exponentials can create problems if you don't use the correct syntax. You cannot do this:
>> sym('2^5') ??? Error using ==> sym.sym>char2sym Not a valid symbolic expression.
Instead, you must do this:
>> sym('2^(5)') ans = 2^(5)
MAPLE is thus more picky about what operators you can use than MATLAB.
Symbolic Functions
You can create functions of symbolic variables, not just the variables themselves. This is probably the most intuitive way to do it:
>> syms a b c %declare variables >> f = a + b + c ans = a + b + c
If you do it this way, you can then subsequently perform substitution, differentiation, and so on with respect to any one of these variables.
If you want to create an actual function, it's not much harder:
>> syms a b c >> f(a,b,c) = a + b + c % or f = symfun(a + b + c, [a b c]) if you want to be more explicit f(a, b, c) = a + b + c >> f(1,2,3) ans = 6
Substituting Values into Symbolic Variables
Substitutions can be made into functions of symbolic variables. Suppose you defined the function f = a + b + c and wish to substitute a = 3 into f. You can do this with the following syntax:
>> syms a b c %declare variables >> f = a + b + c; >> subs(f, a, 3) ans = 3+b+c
Notice the form of this function call. The first argument is the name of the function you wish to substitute into. The second can be either the name of the symbolic variable you want to plug in for or its present value, but if you want to avoid confusion they should be the same anyway. The third argument is the value you want to plug in for that variable.
The value you're plugging in need not be a number. You can also plug in other variables (including those already present in the function) by using strings. Using the same f:
>> subs(f, a, 'x') ans = x+b+c >> subs(f, a, 'b') ans = 2*b + c
If x is already a symbolic variable you can omit the quotes (but if it's not you'll get an undefined variable error):
>> syms x >> subs(f,a,x) ans = x+b+c
Multiple substitutions are allowed; to do it, just declare each of them as an array. For example, to plug in 1 for a and 2 for b use:
>> subs(f, [a,b], [1,2]) ans = 3+c
Finally, if you substitute for all of the symbolic values in a function MATLAB automatically changes the value back into a double so that you can manipulate it in the MATLAB workspace.
>> subs(f, [a,b,c], [1,2,3]) ans = 6 >> class(ans) ans = double
Using Functions with Symbolic Matrices as Inputs
Unfortunately, symfun does not seem to allow using a symbolic matrix as a function input. You can manually add each element of the matrix to the list of input variables, or even use subs to iteratively substitute the input values if you're just using a symbolic expression, but both solutions would require typing out all of the indexing. Instead, the simplest path is to declare an anonymous function:
>> A = sym('A',2) % declare a 2x2 symbolic matrix >> sum_elements = @(myMat) myMat(1,1) + myMat(1,2) + myMat(2,1) + myMat(2,2); sum_elements = @(myMat)myMat(1,1)+myMat(1,2)+myMat(2,1)+myMat(2,2) >> sum_elements(A) ans = A1_1 + A1_2 + A2_1 + A2_2
Algebraic Function Manipulations
The symbolic math toolbox allows you several different ways to manipulate functions. First off you can factor a function using 'factor' and multiply it out using 'expand':
>> syms a b >> f = a^2  2*a*b + b^2; >> factor(f); ans = (a  b)^2 >> expand(ans) ans = a^2  2*a*b + b^2
The 'collect' function does the same thing as the 'expand' function but only affects polynomial terms. 'Expand' can also be used to expand trigonometric and logarithmic/exponential functions with the appropriate identities.
The Horner (nested) representation for a function is given by 'horner':
>> horner(f) ans = b^2+(2*b+a)*a
This representation has a relatively low number of operations required for its evaluation compared to the expanded version and is therefore helpful in making calculations more efficient.
A common problem with symbolic calculations is that the answer returned is often not in its simplest form. MATLAB's function 'simple' will perform all of the possible function manipulations and then return the one that is the shortest. To do this do something like:
>> Y = simple(f) Y = (a  b)^2
Algebraic Equations
The symbolic math toolbox is able to solve an algebraic expression for any variable, provided that it is mathematically possible to do so. It can also solve both single equations and algebraic systems.
Solving Algebraic Equations With a Single Variable
MATLAB uses the 'solve' function to solve an algebraic equation. The syntax is solve(f, var) where f is the function you wish to solve and var is the variable to solve for. If f is a function of a single variable you will get a number, while if it is multiple variables you will get a symbolic expression.
First, let us say we want to solve the quadratic equation x^2 = 16 for x. The solutions are x = 4 and x = 4. To do this, you can put the function into 'solve' directly, or you can define a function in terms of x to solve and pass that into the 'solve' function. The first method is rather intuitive:
>> solve('x^2 = 16', x) ans = 4 4 >> solve(x^2  16, x) ans = 4 4
Either of these two syntax works. The first must be in quotes or you get an 'invalid assignment' error. In the second, x must be defined as a symbolic variable beforehand or you get an 'undefined variable' error.
For the second method you assign a dummy variable to the equation you want to solve like this:
>> syms x >> y = x^2  16; >> solve(y, x);
Note that since MATLAB assumes that y = 0 when you're solving the equation, you must subtract 16 from both sides to put the equation into normal form.
Solving Symbolic Functions for Particular Variables
The format for doing this is similar to that for solving for a single variable, but you will get a symbolic function rather than a number as output. There are a couple of things to look out for though.
As an example, suppose that you want to solve the equation y = 2x + 4 for x. The expected solution is x = (y4)/2. Lets see how we can get MATLAB to do this. First let's look at how NOT to do it:
>> syms x >> y = 2*x + 4; >> solve(y, x) ans = 2
What has happened here? The MATLAB toolbox assumes that the 'y' you declared is 0 for the purposes of solving the equation! So it solved the equation 2x + 4 = 0 for x. In order to do what you intended to do you have to put your original equation, y = 2x + 4, into normal form, which is 2x + 4  y = 0. Once this is done, you need to assign a 'dummy' variable like this:
>> syms x y >> S = 2*x + 4  y; %S is the 'dummy' >> solve(S, x) ans = 2 + 1/2*y
This is, of course, the same thing as what we expected. You could also just pass the function into the 'solve' function like this, as done with functions of a single variable:
>> solve('y = 2*x + 4', x);
The first method is preferable, because once it is set up it is much more flexible to changes in the function. In the second method you would have to change every call to 'solve' if you changed the function at all, whereas in the first you only need to change the original definition of S.
Solving Algebraic Systems
The 'solve' command also allows you to solve systems of algebraic equations, and will attempt to return all solutions to these systems. As a first example, let us consider the linear system
a + b = 3 a + 2*b = 6,
which has the solution (a,b) = (0,3). You can tell MATLAB to solve it as follows:
>> syms a b >> f(1) = a + b  3; >> f(2) = a + 2*b  6; >> [A,B] = solve(f(1), f(2)) A = 0 B = 3
If only one output variable is specified but there are multiple equations, MATLAB will return the solutions in a struct array:
>> SOLUTION = solve(f(1), f(2)) SOLUTION = a: [1x1 sym] b: [1x1 sym] >> SOLUTION.a a = 0 >> SOLUTION.b b = 3
The good thing about this is that the fields have the same names as the original variables, whereas in the other form it is easy to get confused which variable is going into which spot in the array. In addition, the struct array is more convenient for large systems.
Now let us look at a slightly more complex example:
a^2 + b^2 = 1 a + b = 1
This has solutions (a,b) = (0,1) and (a,b) = (1,0). Now putting this into MATLAB gives:
>> f = [a^2 + b^2  1, a + b  1]; SOLUTION = solve(f(1), f(2)); >> SOLUTION.a ans = 1 0 >> SOLUTION.b ans = 0 1
Here both solutions are given, a(1) corresponds to b(1) and a(2) corresponds to b(2). To get one of the solutions into a single array together you can use normal array indexing, as in:
>> Solution1 = [SOLUTION.a(1), SOLUTION.b(1)] Solution1 = [1, 0]
Analytic Calculus
MATLAB's symbolic toolbox, in addition to its algebraic capabilities, can also perform many common calculus tasks, including analytical integration, differentiation, partial differentiation, integral transforms, and solving ordinary differential equations, provided the given tasks are mathematically possible.
Differentiation and Integration with One Variable
Differentiation of functions with one or more variables is achieved using the 'diff' function. As usual, you can either define the function before the differentiation (recommended for M files) or you can manually write it in as an argument (recommended for commandline work). If there is only one symbolic variable in the expression, MATLAB assumes that is the variable you are differentiating with respect to. The syntax is simply:
>> syms x >> f = x^2  3*x + 4; >> diff(f) % or diff('x^2  3*x + 4') ans = 2*x  3
Integration, similarly, is achieved using the 'int' function. Only specifying the function results in an indefinite integral, or the antiderivative of the function.
>> int(f) ans = x^3/3  (3*x^2)/2 + 4*x
Note that if you only specify one output argument (or none at all), the 'int' function omits the integration constant. You just have to know it's there.
To do a definite integral on a onevariable function, simply specify the beginning and end points.
>> int(f, 0,1) ans = 17/6
Differentiation and Integration of Multivariable Functions
A convenient way of representing the derivatives of multivariate functions (partial derivatives) is with the Jacobian, which is performed by the 'jacobian' function. To use it, you should define an array of symbolic functions and then just pass it to the function (note the difference between the use of this function, which requires all equations to be in the same array, and the use of 'solve', which requires you to separately pass each equation):
>> syms a b >> f = [a^2 + b^2  1, a + b  1]; >> Jac = jacobian(f) Jac = [ 2*a, 2*b] [ 1, 1]
Note that the first row is the gradient of f(1) and the second the gradient of f(2).
If you only want a specific partial derivative, not the entire Jacobian, you can call the 'diff' function with the function you want to differentiate and the variable you wish to differentiate with respect to. If none is specified, differentiation occurs with respect to the variable closest to 'x' in the alphabet.
>> diff(f(1), a) ans = 2*a
It is worth noting that to complete an implicit differentiation, one can explicitly state the implicit assumption by multiplying the differentiated function by , where is the ith variable in a multivariable equation.
Indefinite integration of multivariate functions works the same as for single functions; pass the function and MATLAB will return the indefinite integral with respect to the variable closest to x:
>> int(f(1)) ans = a^2*b+1/3*b^3b
This is the integral with respect to b. To avoid confusion, you can specify the variable of integration with a second argument, as with differentiation.
>> int(f(1), a) ans = 1/3*a^3+b^2*aa
Definite integration (as far as I can tell) can only be done with respect to one variable at a time, and this is done by specifying the variable, then the bounds:
>> int(f(1), a, 1, 2) %integrate a from 1 to 2, holding b constant ans = 4/3 + b^2
Analytic Solutions to ODEs
MATLAB can solve some simple forms of ODEs. Unlike with the integration and algebraic solving techniques, the syntax for the differential equation solver requires that you put the function in manually in a specific manner. The derivatives must be specified using the symbol 'DNV', where N is the order of the derivative and V is the variable that is changing. For example, suppose you seek the solution to the equation , the solutions to which are of the form x(t) = A*cos(t) + B*sin(t). You would put this equation into the 'dsolve' function as follows:
>> syms x >> dsolve('D2x = x') ans = C1*sin(t)+C2*cos(t)
Unlike the 'int' function, dsolve includes the integration constants. To specify initial conditions, just pass extra arguments to the 'dsolve' function as strings. If x'(0) = 2 and x(0) = 4 these are inserted as follows:
>> dsolve('D2x = x', 'Dx(0) = 2', 'x(0) = 4') ans = 2*sin(t)+4*cos(t)
Note that the initial conditions must also be passed as strings.
MATLAB can also solve systems of differential equations. An acceptable syntax is to pass each equation as a separate string, and then pass each initial condition as a separate string:
>> SOLUTION = dsolve('Df=3*f+4*g', 'Dg =4*f+3*g', 'f(0) = 0', 'g(0) = 1') SOLUTION = f: [1x1 sym] g: [1x1 sym] >> SOLUTION.f SOLUTION.f = exp(3*t)*sin(4*t) >> SOLUTION.g SOLUTION.g = exp(3*t)*cos(4*t)
The 'dsolve' function, like 'solve', thus returns the solution as a structure array, with field names the same as the variables you used. Also like 'solve', you can place the variables in separate arrays by specifying more than one output variable.
Integral Transforms
MATLAB's symbolic math toolbox lets you find integral transforms (in particular, the Laplace, Fourier, and Ztransform) and their inverses when they exist. The syntax is similar to the other symbolic math functions: declare a function and pass it to the appropriate functions to obtain the transform (or inverse). The GUIDE Toolbox provided by MATLAB allows advanced MATLAB programmers to provide Graphical User Interfaces to their programs. GUIs are useful because they remove end users from the command line interface of MATLAB and provide an easy way to share code across nonprogrammers. In addition by using special compilers the mathematical ability of MATLAB seamlessly blends in with the GUI functionality provided. Just to provide an example, assume you are writing a nonlinear fitting system based on the levenburg marquardt algorithm. Implementing a same GUI in VC++ would take at least a month of effort. But in MATLAB with the existing nlinfit function the time for such an endeavor would be hours instead of days.
The figure shows an example of a simple GUI created with the GUIDE toolbox, it takes as input two numbers adds them and displays them in the third textbox, very simple but it helps illustrate the fact that such a GUI was created in minutes. The first section we need to understand is the concept of a callback
CallBack
A callback is a functions executed whenever the user initiates an action by clicking for example on a button or pressing a key on the keyboard. Programming a callback is therefore the most important part of writing a GUI. For example in the GUI illustrated above, we would need to program a callback for the button Add. This is provided as a callback in the code. The code is provided below and illustrates how to write a simple callback.
%  Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved  to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
n1 = get(handles.edit2,'string');
n2 = get(handles.edit1,'string');
S = str2double(n1) + str2double(n2);
set(handles.edit3,'String',num2str(S))
In this piece of code I get the numbers as strings from the edit boxes and then convert them into numbers using the str2double function provided in MATLAB. I then set the string for the other edit box as the sum of these two numbers. This completes the simple example of a GUI needed to add two numbers. To illustrate a more complex example I show how a simple exponential function can be plotted and you can change the function's parameters. With a little bit of imagination you could make it plot any arbitrary function you enter. To make the example even more complex I have two GUIs, one is the control GUI and the other is the plotting GUI, this allows the user to program some of the more complicated functionality expected out of the modern GUI systems.
Sample Time Colors
By selecting Format>Sample Time Colors, you can get Simulink to color code signal lines according to their sample times. Colors are only updated when the model is updated or simulated.
The most common colors are:
Magenta  Constant 
Black  Continuous 
Red  Fastest Discrete Sample Time 
Yellow  Hybrid/Mixed Sample Time 
For the rest of the colors and other information, see Enabling Sample Time Colors (the Mathworks website)
Note: Constant sample time will only be displayed if Inline Parameters is checked in the Advanced Tab of Simulation>Simulation Parameters. This is because constant blocks can have variables as their arguments.
Wiki Is Moving
We are in the process of moving the Psychtoolbox Wiki to a new location. Please help out by moving parts there and deleting from here. Items that used to be here and are no longer so have already been moved to the new wiki.
Programming
 Differences Between Psychtoolbox Versions Specifies the difference between versions for OS 9, OS X, and Windows
 Version independent scripts  Scripts to allow you to write programs that run on all versions of psychtoolbox.
 Windows only scripts  Scripts only useful when using the Windows port.
 Screen  One of the most used functions in the Psychtoolbox. This function takes different commands and parameters depending upon what you want to do (such as drawing a rectangle, text, etc.).
 Example Code  Examples and useful code snippets.
As of July 15, 2009 Wikibooks has moved to a duallicensing system that supersedes the previous GFDL only licensing. In short, this means that text licensed under the GFDL only can no longer be imported to Wikibooks, retroactive to 1 November 2008. Additionally, Wikibooks text might or might not now be exportable under the GFDL depending on whether or not any content was added and not removed since July 15. 
Version 1.3, 3 November 2008 Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
0. PREAMBLE
The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.
This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
1. APPLICABILITY AND DEFINITIONS
This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a worldwide, royaltyfree license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.
A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.
A "Secondary Section" is a named appendix or a frontmatter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.
The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.
The "Cover Texts" are certain short passages of text that are listed, as FrontCover Texts or BackCover Texts, in the notice that says that the Document is released under this License. A FrontCover Text may be at most 5 words, and a BackCover Text may be at most 25 words.
A "Transparent" copy of the Document means a machinereadable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque".
Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standardconforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machinegenerated HTML, PostScript or PDF produced by some word processors for output purposes only.
The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.
The "publisher" means any person or entity that distributes copies of the Document to the public.
A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition.
The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.
2. VERBATIM COPYING
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly display copies.
3. COPYING IN QUANTITY
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: FrontCover Texts on the front cover, and BackCover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machinereadable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computernetwork location from which the general networkusing public has access to download using publicstandard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
4. MODIFICATIONS
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:
 Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission.
 List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement.
 State on the Title page the name of the publisher of the Modified Version, as the publisher.
 Preserve all the copyright notices of the Document.
 Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.
 Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below.
 Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice.
 Include an unaltered copy of this License.
 Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence.
 Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission.
 For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein.
 Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles.
 Delete any section Entitled "Endorsements". Such a section may not be included in the Modified version.
 Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section.
 Preserve any Warranty Disclaimers.
If the Modified Version includes new frontmatter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.
You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.
You may add a passage of up to five words as a FrontCover Text, and a passage of up to 25 words as a BackCover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of FrontCover Text and one of BackCover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
5. COMBINING DOCUMENTS
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements".
6. COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
7. AGGREGATION WITH INDEPENDENT WORKS
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.
8. TRANSLATION
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.
If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.
9. TERMINATION
You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License.
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.
10. FUTURE REVISIONS OF THIS LICENSE
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document.
11. RELICENSING
"Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site.
"CCBYSA" means the Creative Commons AttributionShare Alike 3.0 license published by Creative Commons Corporation, a notforprofit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization.
"Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document.
An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008.
The operator of an MMC Site may republish an MMC contained in the site under CCBYSA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing.
How to use this License for your documents
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
 Copyright (c) YEAR YOUR NAME.
 Permission is granted to copy, distribute and/or modify this document
 under the terms of the GNU Free Documentation License, Version 1.3
 or any later version published by the Free Software Foundation;
 with no Invariant Sections, no FrontCover Texts, and no BackCover Texts.
 A copy of the license is included in the section entitled "GNU
 Free Documentation License".
If you have Invariant Sections, FrontCover Texts and BackCover Texts, replace the "with...Texts." line with this:
 with the Invariant Sections being LIST THEIR TITLES, with the
 FrontCover Texts being LIST, and with the BackCover Texts being LIST.
If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.
If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.