MatLab Guide Wikibooks
MatLab Guide Wikibooks
PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information. PDF generated at: Sat, 16 Jun 2012 08:20:33 UTC
Contents
Articles
MATLAB Programming Saving and loading a MAT-file Basic Reading and Writing data from a file Boolean and Rational Strings Portable Functions Complex Numbers Arrays Introduction to array operations Struct Arrays Cell Arrays Sparse Matrices Graphics Annotate Scripts Comments Entering data at the command line Loops and Branches Error Messages MATLAB Caveats Debugging M Files Simple matrix manipulation More complicated matrix operations Ordinary Differential Equations Partial Differential Equations Reading and writing from files Writing and Reading to A Serial Port Writing to a USB port Filtering Controls Struct arrays MATlab Classes GNU Octave Differences between Octave and MATLAB 1 5 7 9 12 16 17 19 21 28 30 31 31 33 34 37 38 38 39 47 47 49 51 52 54 55 57 58 58 61 61 63 63 65
71 78 79 80
References
Article Sources and Contributors Image Sources, Licenses and Contributors 81 82
Article Licenses
License 83
MATLAB Programming
MATLAB Programming
MATLAB is a programming language developed by MathWorks. It started out as a matrix programming language where linear algebra programming was simple. It can be run both under interactive sessions and as a batch job. Most MATLAB scripts and functions can be run in the open source programme octave. This is freely available for most computing platforms. GNU Octave and LabVIEW MathScript are systems for numerical computations with an m-file script language that is mostly compatible with MATLAB. Both alternatives can replace MATLAB in many circumstances. While a good deal of the content of this book will also apply to both Octave and LabVIEW MathScript, it is not guaranteed to work in exactly the same manner. Differences and comparison between MATLAB and Octave are presented in Comparing Octave and MATLAB.
MATLAB Programming
Graphics
Graphics
Plot Polar Plot Mesh Semilogx or Semilogy Loglog Bode Plot Nichols Plot Nyquist Plot
Handle Graphics
What is a handle? Figure handles Axis handles Other types of handles
Annotating Plots
Inserting Newlines into Plot Labels
M-file Programming
Scripts
Comments The Input Function
Control Flow
Loops and Branches
Error Messages
MATLAB Caveats Inserting Newlines into Disp Warn and Error
MATLAB Programming
Numerical Manipulation
Linear Algebra
It is the Matrix laboratory after all. Simple matrix manipulation Operations Transpose Systems of linear equations More complicated matrix operations Row reduced echelon form Inverse Coffactor, minor Jacobian
Differential Equations
Ordinary Differential Equations Partial Differential Equations
Examples
Filtering
Moving Average Alpha Beta Kalman PSD estimation Entropy Markov Processes Queuing Theory
Phase vocoder
See "Phase vocoder and encoder in MATLAB" for an example phase vocoder and the corresponding sound sample encoder in MATLAB.
MATLAB Programming While in MATLAB, this can be done with m-script, in Octave new objects are implemented as C++ classes. A simple example of how objects can be added to Octave can be found here [1].
Legacy Toolboxes
GUIDE allows the creation of interactive user interfaces. Simulink is for modeling, simulating and analysing systems. Psychtoolbox is a set of tools that aid in vision research. Distributed computing- The distributed computing toolbox is a set of tools that aid in distributing models over a cluster. Optimization- The optimization toolbox includes various algorithms for minimization.
Matlab in medicine
Image Processing in Optical Coherence Tomography using Matlab is a book which will introduce you to subtleties related to the implementation of selected fragments of algorithms, the notation of some of them in the Matlab environment has been given. The presented source code is shown only in the form of example of implementable selected algorithm. The book is addressed to ophthalmologists , IT specialists and students involved in the development of applications designed for automation of measurements for the needs of medicine.
References
MATLAB documentation [2] from The MathWorks. MATLAB programs compilation [3] from 'Matlab programs for Engineering Students'.
External links
MATLAB at literateprograms.org [4] ControlTheoryPro.com MATLAB Category [5] Processing in Optical Coherence Tomography using Matlab [6] programs compilation for Engineering Students [7]
MATLAB Programming
Other Wikibooks
A number of other wikibooks use MATLAB to teach their subjects. The following wikibooks make use of MATLAB: Signals and Systems Control Systems
References
[1] [2] [3] [4] [5] [6] [7] http:/ / wiki. octave. org/ wiki. pl?CodaTypes http:/ / www. mathworks. com/ access/ helpdesk/ help/ techdoc/ matlab. html http:/ / engineering-matlab. blogspot. in http:/ / en. literateprograms. org/ Category:Programming_language:Matlab http:/ / wikis. controltheorypro. com/ index. php?title=Category:MATLAB http:/ / www. octnews. org/ articles/ 2932585/ image-processing-in-optical-coherence-tomography-u/ :Image http:/ / engineering-matlab. blogspot. in/ :Matlab
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
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 m-file function, the m-file 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.
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.txt', '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.
Basic Reading and Writing data from a file >> load('mySave.mat', 'myData*') Get a cell array of variables in saved file. >> whos('-file', 'mySave.mat')
External Resources
ControlTheoryPro.com [5] MatlabCodes.Webs.com [1]
References
[1] http:/ / matlabcodes. webs. com?title=Category:MATLAB
Boolean and Rational 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.
10
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
11
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.
Strings
12
Strings
Declaring Strings
Besides numbers, MATLAB can also manipulate strings. They should be enclosed in single quotes: >> fstring = 'hello' fstring = hello If you would like to include a single quote this is one way to do it: >> fstring = '''' fstring = ' >> fstring = 'you''re' fstring = you're An important thing to remember about strings is that MATLAB treats them as array of characters. To see this, try executing the following code: >> fstring = 'hello'; >> class(fstring) ans = char Therefore, many of the array manipulation functions will work the same with these arrays as any other, such as the 'size' function, transpose, and so on. You can also access specific parts of it by using standard indexing syntax. Attempting to perform arithmetic operations on character arrays converts them into doubles. >> fstring2 = 'world'; >> fstring + fstring2 ans = 223 212 222
216
211
These numbers come from the standard numbers for each character in the array. These values are obtained by 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 integer-valued 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 Since the MATLAB strings are treated as character arrays, they have some special functions if you wish to compare the entire string at once rather than just its components: 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 [].
Strings strrep(string1, replaced, replacement) replaces all instances of replaced in string1 with replacement
13
Strings
14
Strings >> 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 regular-expresions.info [1] and the MATLAB documentation for the matlab-specific 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.
15
Comparing strings
Unlike with rational arrays, strings will not be compared correctly with the relational operator, because this will treat the string as an array of characters. To get the comparison you probably intended, 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.
References
[1] http:/ / www. regular-expressions. info/
Portable Functions
16
Portable Functions
This section discusses anonymous functions and function handles. Both of these are portable in that rather than having to write an equation multiple times in a program, you can just define it once and then call it whenever you want to use it. In addition, function handles in particular allow you to pass an equation to another function for direct evaluation as needed. Anonymous functions are useful for command-line evaluation or for multiple evaluations in the same m-file.
Anonymous functions
An anonymous function can be created at the command or in a script: >>f = @(x) 2*x^2-3*x+4; >>f(3) ans = 13 To make an anonymous function of multiple variables, use a comma-separated list to declare the variables: >>f = @(x,y) 2*x*y; >>f(2,2) ans = 8 It is possible to make an array of anonymous functions in MATLAB 7.1 but this will become outdated soon so using this construct in a distributed program is not recommended. To pass anonymous functions to other functions, just use the name of the anonymous function in your call: >> f = @(t,x) x; >> ode45(f, [0:15],1)
Function Handles
A function handle passes an m-file 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 m-file (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 m-file to a function, you must first write the m-file, 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 m-file, thus allowing you to do things like solve systems of ODEs rather than only one. Anonymous functions limit you to one equation.
Portable Functions
17
Complex Numbers
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.
Complex Numbers
18
Arrays
19
Arrays
Introduction to Arrays
Arrays are the fundamental data type of MATLAB. Indeed, the former data types presented here, strings and number, are particular cases of arrays. As in many traditional languages, arrays in MATLAB are a collection of several values of the same type (by default, the type is equivalent to the C type double on the same architecture. On x86 and powerpc, it is a floating point value of 64 bits). They are indexed through the use of a single integer or, to get more than one value, an array of integers..
Declaring Arrays
Row and Column Arrays
A simple way to create a row array is to give a comma separated list of values inside brackets: >> array = [0, 1, 4, 5] array = 0 1 4 5 The commas can be omitted for a row array because MATLAB will assume you want a row array if you don't give it any separators. However, the commas make it easier to read and can help with larger arrays. The commas indicate that the array will be a horizontal array. To make a column array you can use semicolons to separate the values. >> column = [1; 2; 3] column = 1 2 3 All elements of an array must be the same data type, so for example you cannot put a function handle and a double in the same array.
Arrays
20
Arrays >> 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.
21
Basics
How to input an array
The common way to input an array from the matlab command line is to put the input figures into list into square brackets: >> [1, 2, 3] ans = 1 2 3
Comma is used to separate columns elements, and semicolon is used to separate rows. So [1, 2, 3] is a row vector, and [1; 2; 3] is a column vector
Introduction to array operations >> [1; 2; 3] ans = 1 2 3 If a blankspace is used to separate elements, the default separator is comma, thus making the vector a row vector. Logically, inputting a matrix is done by using a comma separated list of column vectors, or a semicolon separated list of row vectors: >> [1, 2, 3; 4, 5, 6] ans = 1 4 2 5 3 6
22
Variable assignment
To reuse an array in subsequent operations, one should assign the array to a variable. Variable assignment is done through the equal symbol: >> a = [1, 2, 3] a = 1 2 3
Notice that instead of ans =, the name of the variable is displayed by matlab. If you forget to assign the last statement to a variable, the variable ans always point to the last non assigned: >> [1, 2, 3] ans = 1 >> a = ans a = 1 But: >> [1, 2, 3] ans = 1 2 3 2 3 2 3
23
I.e. ans is really the last non assigned result, and not the result of the last statement. As it is the case for most interpreted languages, you do not need to declare a variable before using it, and reusing a variable name in an assignment will overwrite the previous content. To avoid cluttering the command line of matlab, you can postfix any command with a semicolon: >> a = [1, 2, 3];
24
>> a(2, 1) ans = 3 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 than in Fortran, and the contrary of the order in the C language. >> a = [1, 2, 3; 4, 5, 6]; >> a(3) ans = 2 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 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 =
25
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
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
The multiplication by a scalar also works as expected: >> 2 * [1, 2, 3] ans = [2, 4, 6] 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
26
ans = 7 15 10 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 1 0 0
>> a / b Warning: Matrix is singular to working precision. ans = Inf Inf Inf Inf
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.
Introduction to array operations Non-square 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.
27
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.
Struct Arrays
28
Struct Arrays
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 case-sensitive. 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. >> b.c = 'test' b = b: 0 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'); >> a(2).b = 1; >> a(2).c = 'testing' a = 1x2 struct array with fields: b c >> a(1) ans = b: 0 c: 'test' >> a(2) ans = b: 1 c: 'testing' % The second element % Initial structure % Create structure % Turn it into an array by creating another element
Struct Arrays
29
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
External Resources
ControlTheoryPro.com [1]
References
[1] http:/ / wikis. controltheorypro. com/ index. php?title=Structures
Cell Arrays
30
Cell Arrays
Introduction
Cell arrays are created just like regular arrays except that curly brackets are used instead of square brackets. array = [1, 2, 3; 4, 5, 6]; cell_array = {1, 2, 3; 4, 5, 6}; The array variable is 1 array with 2 rows and 3 columns. Each element is a scalar. The cell_array variable is essentially an array of arrays. In this case the cell_array variable is made up of 6 arrays with 1 scalar element in each of the 6 arrays. Cell arrays have fewer limitations than regular arrays. The regular array, defined by the square brackets, can hold numbers or strings but if it holds strings in each element all the strings must be the same length. Also, if 1 element of an array is a string 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 the lack of limitations/rules for the content of a cell array comes complications. These cell arrays are very powerful tools but take a lot of time to get used to because each element can be almost anything. Cell arrays can also be dynamically resized--a key feature in more advanced data structures. For example, one can create a queue data structure using the commands: cell_array{end+1}='a'; cell_array{end+1}='b'; ... etc. Once can pop an element from the front of the queue using the commands: cell_array(1)=[]; % remove first element - resize cell_array(1)=[]; % remove first element - resize ... etc.
External Links
ControlTheoryPro.com [1]
References
[1] http:/ / wikis. controltheorypro. com/ index. php?title=Cell_Arrays
Sparse Matrices
31
Sparse Matrices
A Sparse Matrix is a matrix that mostly contains zeros. In Matlab, sparse matrices contrast regular ones in the way they are stored, such that memory is used more efficiently for matrices that are sparse. A regular matrix can be converted to a sparse matrix using >> S = sparse(A); % Create sparse representation of A
Sparse matrices are very common in engineering purposes. This is useful for manipulation as most of the matrix has a value of 0.
Graphics
2D Graphics
Plot
Plots a function in Cartesian Coordinates, x and y. Example: x=0:0.1:2; % creates a line vector from 0 to 2 fx=(x+2)./x.^2; % creates fx plot(x,fx,'-ok') % plots 2d graphics of the function fx To plot 2 or more graphs in one Figure, then simply append the second (x,y) pair to the first: >>>x1 = [1,2,3,4] >>>y1 = [1,2,3,4] >>>y2 = [4,3,2,1] >>>plot(x1,y1,x1,y2) This will plot y1 and y2 on the same x-axis in the output.
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 easy to see three dimensional 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 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];
Graphics d=[ 1298 ; 1305.5] plot3(l,f,d); grid on; This example plots a line in 3d. I created this code in an M-file. If you do the same you change the values and hit the run button in the menu bar to see the effect.
32
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
Annotate
33
Annotate
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 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 Object oriented 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 x-axis 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 y-axis of the current plot. It works in same way of xlabel but the output is vertical in 2D plots.
Scripts
34
Scripts
M-files
There are 2 types of m-file Scripts Functions Scripts are a type of m-file 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 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 m-file so long as the necessary variables are present in the m-files 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 M-file 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).
Scripts Path In order to invoke a function that function's m-file must be in the current path. There is a default path that can be setup 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 1st instance of that m-file 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.
35
Scripts
36
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.
External Links
Large parts of this page come from the ControlTheoryPro.com page on M-files [2], Scripts [3], and Functions [4].
References
[1] http:/ / www. mathworks. com/ access/ helpdesk/ help/ techdoc/ index. html?/ access/ helpdesk/ help/ techdoc/ ref/ varargout. html& http:/ / www. google. com/ search?sourceid=navclient& ie=UTF-8& rlz=1T4GFRD_enUS257US258& q=varargout+ MATLAB [2] http:/ / wikis. controltheorypro. com/ index. php?title=M-files [3] http:/ / wikis. controltheorypro. com/ index. php?title=MATLAB_Scripts [4] http:/ / wikis. controltheorypro. com/ index. php?title=MATLAB_Functions
Comments
37
Comments
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 Ctrl-R to (-/ for Mac) place one '%' symbol at the beginning of each line and Ctrl-T (-T for Mac) to do the opposite.
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.
38
Error Messages
39
Error Messages
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 self-explanatory. 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 propogating 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.
Indexing errors
Indexing is a pain in MATLAB, it is probably one of the hardest things to get down, especially since the syntax for an index is the same as the syntax for a function. One annoying fact is that the names of variables are case sensitive, but the names of functions are NOT. So if you make an array called Abs and you try to index abs(1), it will return 1 no matter what the first value in the array Abs is. Unfortunately, MATLAB will not return an error for this (although MATLAB v2008+ or so will return a warning saying that this will be changed in a later version), so a good rule of thumb is never ever name your variables the same as a function. This clears up some indexing problems. Some things are rather obvious but take some practice in avoiding:
Error Messages 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 doesnt 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 starts counting at 1, not 0 like C++. And again, it doesn't tell you which index is not real or logical. Also note that if 0 was a logical 0 (false) then the statement A(0) would be valid and would return all 0 values in the array. Attempting to use non-standard MATLAB syntax in your indexing will often result in the error: >> A(1::, 2) ??? A(1::, 2) | Error: Unexpected MATLAB operator. The "operator" :: is one of several possible operators that MATLAB does not accept. This 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(1:end, 2) ans = 3 Make sure you are careful when using the colon operator, because it does many different things depending on where you put it and misuse often results in these errors. Try putting in one piece of your code at a time and see what it is doing, it may surpise you.
40
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
Error Messages >> 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!
41
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:
Error Messages >> 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. >> 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. Missing [] around left hand side is a likely cause.
42
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 Messages Error: Expression or statement is incorrect--possibly 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.
43
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 and 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 color-coded 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 color-coded 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, becuase 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')
Error Messages 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.
44
Error Messages >> 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.
45
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 function-specific, 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.
Error Messages 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.
46
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.
MATLAB Caveats
47
MATLAB Caveats
1. 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.
Debugging M Files
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 goes 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.
Debugging M Files
48
49
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];
50
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.
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
51
Zero matrix
The "zeros" function produces an array of zeros of a given size. For example, a=zeros(4,3) Produces: a = 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.
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);
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);
52
Ordinary Differential Equations 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 appropriately-sized matrix.
53
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 differential-algebraic equation (this is what the MassSinglular option does; it is usually set to 'maybe' so MATLAB checks by itself).
Ordinary Differential Equations Since ode15i has some differences in its syntax, it is discussed next.
54
55
Delimited files
- textscan, dlmread, dlmwrite
Low-level functions
If you are familiar with reading and writing files in C, these functions will seem familiar. To other users, they are useful if more control is needed over how files are read (or if the built-in and MATLAB contributor central functions fail to read the file).
There are other permissions as well, see the fopen function documentation for more details. By default (if you don't specify a permission), you only have read permission when you open a file. A little note about file ID's in MATLAB: a file identifier will actually be a number, and some numbers have special meanings: fid = -1 ---> cannot open file fid = 1 ---> standard output fid = 2 ---> standard error When you are done with a file, it is a good idea to close it so that other programs can use it, and so you dont accidentally overwrite data. Closing a file is done with the fclose function: >> fclose(fid);
56
Format specifiers
Low-level text reading functions depend on you, the user, to tell them what kind of data is to be read or written. However, they provide a great deal of control over the precision of inputs and outputs and how they are to be labeled. Format specifiers work by providing placeholders, and then providing data to splice into those placeholders. As an eaxmple, the following format specifier indicates that you want to read or write a string in the location specified by %s >> spec = 'Bob has a daughter named %s'; %s is a placeholder for a string. You can also define placeholders for integers (%d), floating-point values (%x.yf, where x is the number of digits to print before the decimal point and y is the number to print afterward), %x for hexadecimal, and so on. Consult the fprintf documentation for details on the supported specifiers. To read a file ("Daughters.txt" ) containing the following text: Bob has a daughter named Jill you would use the following commands: >> fid = fopen('Daughters.txt'); >> spec = 'Bob has a daughter named %s' >> s = fscanf(spec) s = Jill >> fclose(fid); Note that only the string specified by %s is actually returned, but the entire string is read. If the file instead contained the following: Bob has a son named Bob and you ran the same code, you would obtain: >> fid = fopen('Daughters.txt'); >> spec = 'Bob has a daughter named %s' >> s = fscanf(spec); s = >> fclose(fid); Nothing is returned because there are no matches for 'Bob has a daughter named' in the beginning of the file. Note that nothing is returned from the following file as well: Bob has a son named Bob Bob has a daughter named Jill We can only read "Bob has a daughter named Jill" after we have read "Bob has a son named Bob".
Reading and writing from files If you have an all-numeric matrix, the dlmread and dlmwrite functions work just as well unless a certain numeric precision is required for input or output. To read cell arrays from a text file that contain strings, it is recommended to look on MATLAB contributor central for a routine called readtext [1], which is as easy to use as xlsread/xlswrite, and returns results in a comparable format. Reading such files can also be done using the textscan function, as long as the format of all of the lines is consistent (i.e. no columns mixing strings and numeric values, no blank cells, and so on). Similarly, writing cell arrays to text can be performed using this file [2] from MATLAB contributor central. Unfortunately, there is no built-in equivalent to textscan to write formatted data from a cell array to a text file.
57
References
[1] http:/ / www. mathworks. com/ matlabcentral/ fileexchange/ 10946-readtext [2] http:/ / www. mathworks. com/ matlabcentral/ fileexchange/ 25387-write-cell-array-to-text-file
58
further reading
Serial Programming
further reading
Serial Programming:USB Technical Manual+
Filtering
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.
MATLAB implementation(All the code here was intended to be put in an M-file): clc; clear; v=.01 f=100; fs=5000; t=0:1/fs:.03 x=sin(2*pi*f*t); r=sqrt(v)*randn(1,length(t)); Xw=x+r; (filter input) for n= 3:length(Xw), y(n)=sum(Xw(n-2:n))/3; end plot(y); hold;
% clear all
%original signal %noise %signal plus noise % I have chosen h=3 %y[n] is the filtered signal
Filtering plot(x,'r'); over top the 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. %plot the original signal %filtered signal to see
59
Filtering
60
nsamples=tmax/psample+1; +1 because we include t=0 and t=tmax. nsamples=2^ceil(log2(nsamples)); round up to a power of 2 in length so FFT will work. times=(0:psample:(nsamples-1)*psample)'; Create a column vector of sample times.
input x=sin(2*pi*10*times)+sin(2*pi*3*times); Make a 10Hz sine wave plus a 3Hz sine wave
Fourier transform
fft_x=fft(x, length(x));
fft_x_mag=abs(fft_x);
fft_x_phase=unwrap(angle(fft_x));
How do you view the results? plot(frequencies, fft_x_mag); Or, to match the amplitude of the magnitude peak to the amplitude of the sine wave, plot(frequencies, (2/nsamples)*fft_x_mag);
References
Lyons, Richard G. Understanding digital signal processing. Upper Saddle River: Prentice Hall PTR, 2001. ISBN 0-201-63467-8. Chapter 3 discusses the DFT.
Controls
61
Controls
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
Struct arrays
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
Struct arrays 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.
62
MATlab Classes
63
MATlab Classes
MATlab stores methods (separate M-file) 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 M-files.
GNU Octave
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.
GNU Octave
64
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 3 2 4
octave:4> x.c x.c = string Short-circuit boolean operators Octave's `&&' and `||' logical operators are evaluated in a short-circuit 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 C-like increment and decrement operators `++' and `--' in both their prefix and postfix forms. Unwind-protect Octave supports a limited form of exception handling modelled after the unwind-protect form of Lisp. The general form of an unwind_protect block looks like this: unwind_protect body unwind_protect_cleanup cleanup end_unwind_protect Variable-length 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)
GNU Octave disp (va_arg ()); endwhile endfunction Variable-length 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
65
References
http://en.wikipedia.org/wiki/GNU_Octave
Some of the differences that do exist between Octave and MATLAB can be worked around using "user preference variables."[1] 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. Matlab only supports single quotes, which means parsing errors will occur if you try to use double quotes (e.g. in an Octave script when run on Matlab). 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 behave in a slightly more Matlab-compatible way. 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. Tip for sharing .mat files between Octave and Matlab: always use save -V6 if you are using Matlab 7.X. Octave version 2.1.x cannot read Matlab 7.X .mat files. Octave 2.9.x can read Matlab 7.X .mat files.
66
Load
For compatiblility, it is best to specify absolute paths of files for LOAD. Matlab (7.0) vs Octave (2.1.71): paths are not searched for .mat files in the same way as .m files: Matlab a = 1; save /tmp/a.mat a ; addpath('/tmp'); load a.mat % OK Octave a = 1; save /tmp/a.mat a ; LOADPATH=['/tmp:',LOADPATH]; load a.mat % error: load: nonexistent file: `a.mat' For any other purpose, don't use absolute paths. It is bad programming style. Don't do it. It causes many problems.
Temporaries
Octave supports temporary expressions. columns = size(mtx)(2); tmp = size(mtx); columns = tmp(2); % % works in Octave, fails in Matlab works in both
product of booleans
Matlab (7.0) and Octave (3.0.2) responds differently when computing the product of boolean values: X = ones(2,2) ; prod(size(X)==1) Matlab: ??? Function 'prod' is not defined for values of class 'logical'. Octave: ans = 0
nargin
Matlab (7.0) will not allow the following; Octave (2.1.71) will. function a = testfun(c) if (nargin == 1) nargin = 2; end
67
startup.m
Matlab will execute a file named 'startup.m' in the directory it was called from on the command line. Octave does not. It will, however, execute a file named '.octaverc' which can be edited to execute existing files 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 4 matrix where the last element of the last row is a space.
Calling Shells
the "! STRING" syntax calls a shell with command STRING in Matlab. Octave does not recognize !. Always use system(STRING) for compatibility. If you really miss the one-character shortcut, for convenience on the command line you can create a similar shortcut by defining the following in your 2.9.x octave startup file: function S(a), system(a); end mark_as_rawcommand('S') Now "S STRING" will evaluate the string in the shell.
hist
hist.m in Octave has a normalization input, Matlab does not.
68
Whitespace
Matlab doesn't allow whitespace before the transpose operator. [0 1]' works in Matlab, but [0 1] ' doesn't. Octave allows both cases.
Line continuation
Matlab always requires `...' for line continuation. rand (1, ... 2) while both rand (1, 2) and rand (1, \ 2) work in Octave, in addition to `...'.
69
Differences between Octave and MATLAB function f=fcnchk(x, n) f = x; end The main difference is the lack of GUI for Octave. There are several attempts to solve this issue ( Xoctave [2], QtOctave, guioctave, etc.)
70
References
[1] http:/ / www. gnu. org/ software/ octave/ FAQ. html#IDX53 [2] http:/ / www. xoctave. com
http://wiki.octave.org/wiki.pl?MatlabOctaveCompatibility
Symbolic Toolbox
71
Symbolic Toolbox
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 >> a2 >> a a = [ = sym('a1'); = sym('a2'); = [a1, a2] 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:
Symbolic Toolbox >> 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.
72
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 substitutions, differentiations, and so on with respect to any one of these variables.
Symbolic Toolbox >> 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
73
Symbolic Toolbox
74
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.
Symbolic Toolbox 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.
75
Symbolic Toolbox >> 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]
76
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.
Symbolic Toolbox 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.
77
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^3-b 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*a-a 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
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]
Symbolic Toolbox 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.
78
Integral Transforms
MATLAB's symbolic math toolbox lets you find integral transforms (in particular, the Laplace, Fourier, and Z-transform) 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).
GUIDE
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 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 a 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
GUIDE example I show how a simple exponential function can be plotted and you 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.
79
Simulink
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 Red Yellow Continuous Fastest Discrete Sample Time Hybrid/Mixed Sample Time
For the rest of the colors and other information, see Enabling Sample Time Colors (the Mathworks website) [1] 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.
References
[1] http:/ / www. mathworks. com/ access/ helpdesk/ help/ toolbox/ simulink/ ug/ creating_model8. shtml
Psychtoolbox
80
Psychtoolbox
Wiki Is Moving
We are in the process of moving the Psychtoolbox Wiki to a new location [1]. 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.
References
[1] http:/ / www. psychtoolbox. org
81
82
License
83
License
Creative Commons Attribution-Share Alike 3.0 Unported //creativecommons.org/licenses/by-sa/3.0/