Professional Documents
Culture Documents
Published by:
Global Media
1819, Bhagirath Palace,
Chandni Chowk, Delhi-110 006
Email: globalmedia@dkpd.com
Table of Contents
3. Graphics
4. M File Programming
5. Mathematical Manipulations
7. Object-Oriented Programming
9. Toolboxes
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 M-file. 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 left-hand 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 M-file 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:
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
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:
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".
>>open filename.ext
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 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.
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 lead to a lot of wasted
effort a lot of the time, 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
>> 3503-3215
ans =
288
>> 288/10
ans =
28.8
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:
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. If the former is true, you'll
hear an annoying noise and will get 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 bottom-left 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 book are good
places to look for help on what you need to provide as inputs and what you will get back.
BE CAREFUL because 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:
you'll be OK.
Reading and Writing from a file:
Command Line
Reading and Writing data from/to a .mat file
The quickest mean 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 State-Space objects
that were saved using version 7 to a version 6 compatible file. When the file was
opend in MATLAB version 6+ the State-Space objects did not load.Spradlig
(talk) 04:52, 31 March 2008 (UTC)
Saving Data
• Save all workspace data to the file mySave.mat in the current directory.
>> save('mySave.mat')
>> save(fullfile(pwd, 'mySave.mat'))
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'))
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
M-files (usually the work directory) otherwise you get an error. You can specify the path
to a file but, this can get messy.
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.
This works only if the text is entirely numerical, without special formatting. Otherwise
you get a 'unrecognized character' error.
The easiest way to write to a non-excel 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.
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.
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.
Most of the rational operators also work with complex numbers. Complex numbers,
however, cannot be interchanged with boolean values like the real rationals can. See the
complex numbers section for details on how to use them.
%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.
>>%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
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
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
Terminology
Matlab refers to Booleans as "logicals" and does not use the word "Boolean" in code or
documentation.
Declaring Strings
Besides numbers, MATLAB can also manipulate strings. They should be enclosed in
single quotes:
If you would like to include a single quote this is one way to do it:
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.
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.6)
ans = h
>> char(104)
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:
If you want to display a string in the command window in combination with other text
you must use array notation combined with either the 'display' or the 'disp' function:
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:
Any other function that returns a string can also be used in the array.
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:
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:
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.
This section discusses inline functions, anonymous functions, and function handles. Each
of these is 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. Inline and anonymous functions are useful for command-
line evaluation or for multiple evaluations in the same m-file.
Inline functions
An inline function is one way that a function can be created at the command or in a
script:
>>f = inline('2*x^2-3*x+4','x');
>>f(3)
ans = 13
To create a multi-variable inline function, send more inputs to the 'inline' function:
You cannot make an array of inline functions, MATLAB will tell you that you have too
many inputs or do something weird like that.
Anonymous functions
A function can also be created at the command or in a script:
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).
To pass an m-file to a function, you must first write the m-file, say something like this:
Save it as myfunc.m. To pass this to another function, say an ODE integrator, use the @
symbol as follows:
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.
>> compnum = 1 + i
compnum = 1.000 + 1.000i
>> compnum = 1 + j
compnum = 1.000 + 1.000i
>> 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.
>> (-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.
>> 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
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:
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.
In MATLAB the term array is synonymous with matrix and will more often than not be
referred to as a matrix. It should be noted that a matrix, as its mathematical equivalent,
requires all its rows and all its columns to be the same size:
The number of rows and columns of the matrix can be known through the built-in size
function. Following the standard mathematical convention, the first number is the number
of rows and the second is the number of columns:
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. Mono-dimensional arrays
are actually a special case of multi-dimensional 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
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:
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:
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.
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.
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
>> [1; 2; 3]
ans =
1
2
3
If a blankspace is used to seperate elements, the default separator is comma, thus making
the vector a row vector.
Logically, inputing a matrix is done by using a comma separated list of column vectors,
or a semicolon seperated list of row vectors:
>> [1, 2, 3; 4, 5, 6]
ans =
1 2 3
4 5 6
Variable assignment
To reuse an array in subsequent operations, one should assign the array to a variable.
Variable assignement 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 2 3
>> a = ans
a =
1 2 3
But:
>> [1, 2, 3]
ans =
1 2 3
>> b = [4, 5, 6]
b =
4 5 6
>> a = ans
a =
1 2 3
Ie 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 assignement will overwrite the previous
content.
To avoid cluttering the command line of matlab, you can postfix any command with a
semicolon:
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:
ans =
1
>> a(3)
ans =
>> a(5)
??? Index exceeds matrix dimensions.
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:
ans =
>> 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.
ans =
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:
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(:)
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 =
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:
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:
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 substraction as defined in classic vector vectors spaces ,
which is simply the addition and substraction elements wise:
ans =
0 0 2
>> 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:
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. For square matrices, a / b is equivalent to a * b − 1. For example :
ans =
1 0
1 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,
ans =
0 2 6
As matlab is a numerical computing language, you should keep in mind that a matrix
which is theoritically 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.
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.
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,
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.
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 matrix-multiply 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, except 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:
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.
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:
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 n-2 points between 10^a and 10^b as follows:
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:
For example:
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:
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:
Cross Product
The cross product of two vectors of size 3 is computed using the 'cross' function:
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:
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.
Declaring Structures
Structures can be declared using the struct command.
In MATLAB, variables do not require explicit declaration before their use. As a result
structures can be declared with the '.' operator.
Arrays of Structures
Structures can also be arrays. Below is an example
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.
>> 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 the brackets ([]) as seen below.
>> [a.('c')]
ans =
testtesting
>> [a.('b')]
ans =
0 1
Graphics
2D Graphics
Plot
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)
Polar Plot
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 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];
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.
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
Example:
x=[0:pi/90:2*pi]';
y=x';
z=sin(x*y);
contour(x,y,z);
Contourf
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 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:
Examples
Axis Label
>>xlabel('string')
You can display text on two lines or insert the value of variables
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
• 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).
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 m-file name is function_name.m. Calling the
function from the command line or another m-file is done by invoking the m-file 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.
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 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.
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
where min is the minimum number of arguments necesary 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.
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.
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
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.
Comments can also Identify who wrote the code and when they wrote it.
Nested 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 Ctrl-R
to place one '%' symbol at the beginning of each line and Ctrl-T 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,
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:
All of Matlab's own functions written in Matlab are documented this way as well.
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:')
x = 3
>>
Control Flow
IF statement
An IF statement can be used to execute code once 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
case value2
statements
...
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.
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.
FOR statement
The FOR statement executes code a specified number of times using an iterator. Syntax:
for ii = 1:3
statements
end
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.
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.
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.
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-explanitory. As a reminder, here are some common functions that
cannot be performed and what MATLAB returns (along with a warning for each one):
NaN will very often result in errors or useless results unless measures are taken to avoid
propogating them.
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:
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.
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, 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:
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.
Assignment errors
Ah, assignment, that is using the = sign to give a variable, or certain elements of an array,
a particular value.
>> 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,
For such a purpose you should use cell arrays or struct arrays.
>> 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:
>> 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:
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.
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).
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:
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:
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(1
??? A(1
|
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.
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
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.
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.
>> ??? `
|
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.
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 the function with too many input arguments either:
>> A = plus(1,2,3)
??? Error using ==> plus
Too many input arguments.
You can choose how many of the output arguments you want out of those available by
using the bracket notation, but you cannot assign more 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.
Finally, you must make sure that all arguments passed TO the function are the right class,
and all those returned are also the right class if you are replacing parts of an array that
already exists (see the section on assignment for more on this).
If you have too many END statements and more than one function in an M-file,
MATLAB may give you a cryptic message about not formatting the functions correctly.
This is because all functions in the same M-file 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.
Having an extra END in a 'switch' statement gives a message that you used the 'case'
keyword illegaly, 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.
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.
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.
M-file 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 M-file 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 M-file. 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.
Or press CRTL+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
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.
However, sometimes MATLAB won't even let you return to the main window to press
CTRL-C. 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 STRG-C with
MATLAB being able to respond to your command.
Mathematical Manipulations
Linear Algebra
Operations
Squaring a matrix
a=[1 2;3 4];
a^2;
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:
or
Transpose
To find the transpose of a matrix all you do is place a apostrophe after the bracket.
Transpose- switch the rows and columns of a matrix.
Example:
a=[1 2 3]
aTranspose=[1 2 3]'
or
Homogeneous Solutions
Particular Solutions
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
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(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 indecies are
zero.
Example:
a=[1 2 3; 4 5 6];
b=rref(a);
It's that simple. (I believe that MATLAB uses the Gauss-Jordan 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 the matrix must be
square)
Example:
Coffactor, minor
The Jacobian
t=jacobian(e,w);
e is a scalar vector, w is a vector of functions. Also, this does not solve equations
symbolicaly unless you define the w vector functions as symbolics prior to executing this
statment.
Example:
syms x y z;
w=[x y z];
e=[1 2 3];
t=jacobian(e,w);
Differential Equations
To use function handles, you must first create an M-file with the function in it like so:
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):
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:
Calling the ODE function without input arguments gives a graph of the solution. Calling
it with one output argument returns a struct array:
This data is mostly used to, in the future, call the 'deval' function to get the answer at any
time you want:
Deval can also return the derivative at the point of interest by including a second output
argument.
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.
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:
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:
The options structure can then be passed to the ode function as a forth (optional) input
argument:
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).
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
tigheter 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 is the only ODE solver that solves implicit equations, it must have some
special syntactical rules on how to input the function.
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:
This will return similar results to ode45 when used for the explicit equation, but has less
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. MATLAB
Programming/Partial Differential Equations
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 transmitt and recieve 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
ethernet connection (dont laugh I've been in this situation more times than I like to
remember)).
MATLAB provides us with there style of reading and writing to the serial port.
object=serial(port,'Property name',propertyValue);
(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 1-4 (depending
on how many there are). This also includes DB-9, DB-25 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
Example:
Formula:
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)=(Xw(n)+(Xw(n-1))+(Xw(n-2)))/3; %y[n] is the filtered
signal
end
plot(y);
hold;
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 Kalman filter is a recursive method of combining to 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(i-1)+alpha*(Rm(i)-Rs(i-1));
Cs=(1-alpha)*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.
fsample=100;
sample period
tmax=10;
For how long
do you want time range
to sample? run from 0 to 10 sec. inclusive
nsamples=tmax/psample+1;
nsamples=2^ceil(log2(nsamples));
How many
samples does N round up to a power of 2 in length so FFT will
that give you? work.
times=(0:psample:(nsamples-
1)*psample)';
delf=fsample/nsamples;
How far
apart are
each of the frequencies=(0:delf:(nsamples-
frequency- 1)*delf)';
domain result
points?
Column vector of result frequencies
x=sin(2*pi*10*times)+sin(2*pi*3*times);
What signal
do you want input x(t)
to sample? Make a 10Hz sine wave plus a 3Hz sine wave
Fourier transform
What are the fft_x=fft(x, length(x));
results?
What
frequencies
Xm(f) = | X(f) | fft_x_mag=abs(fft_x);
does the
signal have?
What phase fft_x_phase=unwrap(angle(fft_x));
relationships?
plot(frequencies, fft_x_mag);
plot(frequencies,
(2/nsamples)*fft_x_mag);
fft_x_power=fft_x_mag.^2;
What about
the power Xp(f) = | X(f) | 2
spectrum? plot(frequencies, fft_x_power);
Object-Oriented 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:
The fields of a structure and their value 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:
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
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
>> getfield(city,'name')
ans = Liege
>> 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. MATlab stores methods (seperate 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.
Comparing Octave and MATLAB
Octave is a free computer program for performing numerical computations 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 programs consist of a list of function calls or script. The language is matrix-based
and provides various functions for matrix operation. It is not object-oriented, 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.
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:
1 2
3 4
octave:4> x.c
x.c = string
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 `|'.
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
Here is an example of a function that uses the new syntax to print a header followed by
an unspecified number of values:
Octave also has a real mechanism for handling functions that return an unspecified
number of values. For example:
Octave has been mainly built with MATLAB compatibility in mind. It essentially shares
a lot of features in common with MATLAB:
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. 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.
load
For compatablility, 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.
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)
nargin
Matlab (7.0) will not allow the following; Octave (2.1.71) will.
function a = testfun(c)
if (nargin == 1)
nargin = 2;
end
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.
['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:
hist
hist.m in Octave has a normalization input, Matlab does not.
foo = 5;
printf('My result is: %d\n', foo)
works in Octave, but not Matlab. If using Matlab, `fprintf' covers writing both to the
screen and to a file:
foo = 5;
fprintf('My result is: %d\n', foo)
In Matlab, the omission of the optional file-handle argument to fprintf (or using the
special value 1 for standard output or 2 for standard error) causes the text to be printed to
the screen rather than to a file.
Whitespace
Matlab doesn't allow whitespace before the transpose operator.
[0 1]'
[0 1] '
while both
rand (1,
2)
and
rand (1, \
2)
• For not-equal comparison, Octave can use '~=' or '!='. Matlab requires '~=' .
• For a logical-and, Octave can use `&' or `&&'; Matlab requires `&' . (note:
Matlab supports `&&' and `||' as short-circuit logical operators since version 6.5.)
• For a logical-or, Octave can use `|' or `||'; Matlab requires `|' . (note: Octave's '||'
and '&&' return a scalar, '|' and '&' return matrices)
• MATLAB uses the percent sign to begin a comment. Octave uses both the pound
sign and the percent sign interchangeably.
• MATLAB has no fputs function. Call fprintf instead.
• For exponentiation, Octave can use `^' or `**'; Matlab requires `^'.
• For string delimiters, Octave can use ` or "; Matlab requires '.
• For ends, Octave can use `end{if,for, ...}'; Matlab requires `end'.
• If something (like Netlab) need a function called fcnchk you can just put the
following into a file called fcnchk.m and put it somewhere Octave can find it:
function f=fcnchk(x, n)
f = x;
end
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
>> 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.
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.
>> sym('2^-5')
??? Error using ==> sym.sym>char2sym
Not a valid symbolic expression.
>> 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 substitutions, differentiations,
and so on with respect to any one of these 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:
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:
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:
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.
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 effects
polynomial terms. 'Expand' can also be used to expand trigonometric and
logarithmic/exponential functions with the appropriate identities.
>> 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.
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:
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.
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 = (y-4)/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:
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.
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:
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.
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:
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:
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 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 command-line 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 = 1/3*x^3-3/2*x^2
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 one-variable function, simply specify the beginning and end
points.
>> 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
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:
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:
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 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).
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.
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 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.
summary="This table gives the color, sample time pairings for Simulink's sample time
colors.
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.Click here to go back up to the MATLAB
programming book.