7/31/2019 MatLab Guide Wikibooks
1/86
PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information.
PDF generated at: Sat, 16 Jun 2012 08:20:33 UTC
MATLAB Guide WikiBook
7/31/2019 MatLab Guide Wikibooks
2/86
Contents
Articles
MATLAB Programming 1
Saving and loading a MAT-file 5
Basic Reading and Writing data from a file 7
Boolean and Rational 9
Strings 12
Portable Functions 16
Complex Numbers 17
Arrays 19
Introduction to array operations 21
Struct Arrays 28
Cell Arrays 30
Sparse Matrices 31
Graphics 31
Annotate 33
Scripts 34
Comments 37
Entering data at the command line 38
Loops and Branches 38
Error Messages 39
MATLAB Caveats 47
Debugging M Files 47
Simple matrix manipulation 49
More complicated matrix operations 51
Ordinary Differential Equations 52
Partial Differential Equations 54
Reading and writing from files 55
Writing and Reading to A Serial Port 57
Writing to a USB port 58
Filtering 58
Controls 61
Struct arrays 61
MATlab Classes 63
GNU Octave 63
Differences between Octave and MATLAB 65
7/31/2019 MatLab Guide Wikibooks
3/86
Symbolic Toolbox 71
GUIDE 78
Simulink 79
Psychtoolbox 80
References
Article Sources and Contributors 81
Image Sources, Licenses and Contributors 82
Article Licenses
License 83
7/31/2019 MatLab Guide Wikibooks
4/86
MATLAB Programming 1
MATLAB Programming
MATLAB is a programming language developed by MathWorks. It started out as a matrix programming language
where linear algebra programming was simple. It can be run both under interactive sessions and as a batch job.
Most MATLAB scripts and functions can be run in the open source programme octave. This is freely available for
most computing platforms.
GNU Octave and LabVIEW MathScript are systems for numerical computations with an m-file script language that
is mostly compatible with MATLAB. Both alternatives can replace MATLAB in many circumstances. While a good
deal of the content of this book will also apply to both Octave and LabVIEW MathScript, it is not guaranteed to
work in exactly the same manner. Differences and comparison between MATLAB and Octave are presented in
Comparing Octave and MATLAB.
Basic MATLAB Concepts
Saving and loading a MAT-file Commands
File Naming conventions
Basic Reading and Writing data from a file
The MATLAB Command Prompt
Calculator
Data Storage and Manipulation
Data Types and Operators on Point Values
Boolean and Rational
Strings
Portable Functions
Complex Numbers
Arrays and Matrices
What is an array?
Introduction to array operations
Vectors and Basic Vector Operations
Mathematics with Vectors and Matrices
Struct Arrays
Cell Arrays
Sparse Matrices
http://en.wikibooks.org/w/index.php?title=File:00%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Sparse_Matriceshttp://en.wikibooks.org/w/index.php?title=File:00%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Cell_Arrayshttp://en.wikibooks.org/w/index.php?title=File:00%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Struct_Arrayshttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Vectoring_Mathematicshttp://en.wikibooks.org/w/index.php?title=File:75%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Basic_vector_operationshttp://en.wikibooks.org/w/index.php?title=File:75%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Introduction_to_array_operationshttp://en.wikibooks.org/w/index.php?title=File:75%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Arrayshttp://en.wikibooks.org/w/index.php?title=File:75%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Complex_Numbershttp://en.wikibooks.org/w/index.php?title=File:50%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Portable_Functionshttp://en.wikibooks.org/w/index.php?title=File:75%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Stringshttp://en.wikibooks.org/w/index.php?title=File:75%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Boolean_and_Rationalhttp://en.wikibooks.org/w/index.php?title=File:50%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/The_MATLAB_Command_Prompthttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Basic_Reading_and_Writing_data_from_a_filehttp://en.wikibooks.org/w/index.php?title=File:50%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Saving_and_loading_a_MAT-filehttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/An_alternative_to_MATLAB:_Octavehttp://en.wikipedia.org/wiki/GNU_Octavehttp://en.wikipedia.org/wiki/LabVIEWhttp://en.wikipedia.org/wiki/GNU_Octavehttp://en.wikibooks.org/w/index.php?title=Octavehttp://en.wikipedia.org/wiki/The_MathWorkshttp://en.wikipedia.org/wiki/MATLAB7/31/2019 MatLab Guide Wikibooks
5/86
MATLAB Programming 2
Graphics
Graphics
Plot
Polar Plot
Mesh Semilogx or Semilogy
Loglog
Bode Plot
Nichols Plot
Nyquist Plot
Handle Graphics
What is a handle?
Figure handles
Axis handles
Other types of handles
Annotating Plots
Inserting Newlines into Plot Labels
M-file Programming
Scripts
Comments
The Input Function
Control Flow
Loops and Branches
Error Messages
MATLAB Caveats
Inserting Newlines into Disp Warn and Error
http://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Inserting_Newlines_into_Disp_Warn_and_Errorhttp://en.wikibooks.org/w/index.php?title=File:00%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/MATLAB_Caveatshttp://en.wikibooks.org/w/index.php?title=File:75%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Error_Messageshttp://en.wikibooks.org/w/index.php?title=File:25%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Loops_and_Brancheshttp://en.wikibooks.org/w/index.php?title=File:75%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Control_Flowhttp://en.wikibooks.org/w/index.php?title=File:50%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Entering_data_at_the_command_linehttp://en.wikibooks.org/w/index.php?title=File:50%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Commentshttp://en.wikibooks.org/w/index.php?title=File:25%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Scriptshttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Inserting_Newlines_into_Plot_Labelshttp://en.wikibooks.org/w/index.php?title=File:25%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Annotatehttp://en.wikibooks.org/w/index.php?title=File:25%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Handle_Graphicshttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Nyquist_Plothttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Nichols_Plothttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Bode_Plothttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Logloghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Semiloghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Meshhttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Polar_Plothttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Plothttp://en.wikibooks.org/w/index.php?title=File:25%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Graphics7/31/2019 MatLab Guide Wikibooks
6/86
MATLAB Programming 3
Numerical Manipulation
Linear Algebra
It is the Matrix laboratory after all.
Simple matrix manipulation
Operations
Transpose
Systems of linear equations
More complicated matrix operations
Row reduced echelon form
Inverse
Coffactor, minor
Jacobian
Differential Equations Ordinary Differential Equations
Partial Differential Equations
More advanced I/O
Different versions of MATLAB handle this differently. We will focus on versions 6.5 and 7.x, primarily on
MATLAB 7.x since it is the latest. A note will appear when the procedure is different for ver. 6.
Examples
Filtering
Moving Average
Alpha Beta
Kalman
PSD estimation
Entropy
Markov Processes
Queuing Theory
Phase vocoder
See "Phase vocoder and encoder in MATLAB" for an example phase vocoder and the corresponding sound sample
encoder in MATLAB.
Object Oriented Programming
MATLAB as well as Octave have object oriented capabilities. Yet, technically it is not fully an object oriented
language.
An Object Oriented Language(OOL) has three components: 1. Polymorphism 2. Inheritance 3. Encapsulation
Octave can be extended by adding new objects. Those objects can overload the operators like e.g. assignment,slicing, comparison.
http://en.wikipedia.org/wiki/Phase_vocoderhttp://en.wikibooks.org/w/index.php?title=File:25%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Filteringhttp://en.wikibooks.org/w/index.php?title=File:00%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Partial_Differential_Equationshttp://en.wikibooks.org/w/index.php?title=File:50%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Ordinary_Differential_Equationshttp://en.wikibooks.org/w/index.php?title=File:50%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/More_complicated_matrix_operationshttp://en.wikibooks.org/w/index.php?title=File:50%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Simple_matrix_manipulation7/31/2019 MatLab Guide Wikibooks
7/86
MATLAB Programming 4
While in MATLAB, this can be done with m-script, in Octave new objects are implemented as C++ classes. A
simple example of how objects can be added to Octave can be found here[1]
.
An alternative to MATLAB: Octave
What is Octave ?A short presentation of Octave and its history.
Differences between Octave and MATLAB
The most important differences between Octave and MATLAB that anyone willing to use Octave instead of
MATLAB should be aware of.
Toolboxes and Extensions
The toolboxes are pretty good if you can afford them. In version 7 there are a lot of toolboxes.
Legacy Toolboxes
GUIDE allows the creation of interactive user interfaces.
Simulink is for modeling, simulating and analysing systems.
Psychtoolbox is a set of tools that aid in vision research.
Distributed computing- The distributed computing toolbox is a set of tools that aid in distributing models over a
cluster.
Optimization- The optimization toolbox includes various algorithms for minimization.
Matlab in medicine
Image Processing in Optical Coherence Tomography using Matlab is a book which will introduce you to subtleties
related to the implementation of selected fragments of algorithms, the notation of some of them in the Matlab
environment has been given. The presented source code is shown only in the form of example of implementable
selected algorithm. The book is addressed to ophthalmologists , IT specialists and students involved in the
development of applications designed for automation of measurements for the needs of medicine.
References
MATLAB documentation[2]
from The MathWorks.
MATLAB programs compilation[3]
from 'Matlab programs for Engineering Students'.
External links
MATLAB at literateprograms.org[4]
ControlTheoryPro.com MATLAB Category[5]
Processing in Optical Coherence Tomography using Matlab[6]
programs compilation for Engineering Students[7]
http://engineering-matlab.blogspot.in/:Matlabhttp://www.octnews.org/articles/2932585/image-processing-in-optical-coherence-tomography-u/:Imagehttp://wikis.controltheorypro.com/index.php?title=Category:MATLABhttp://en.literateprograms.org/Category:Programming_language:Matlabhttp://engineering-matlab.blogspot.in/http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.htmlhttp://en.wikibooks.org/w/index.php?title=File:00%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Psychtoolboxhttp://en.wikibooks.org/w/index.php?title=File:00%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Simulinkhttp://en.wikibooks.org/w/index.php?title=File:00%25.svghttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/GUIDEhttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Differences_between_Octave_and_MATLABhttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/GNU_Octavehttp://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Comparing_Octavehttp://wiki.octave.org/wiki.pl?CodaTypes7/31/2019 MatLab Guide Wikibooks
8/86
MATLAB Programming 5
Other Wikibooks
A number of other wikibooks use MATLAB to teach their subjects. The following wikibooks make use of
MATLAB:
Signals and Systems
Control Systems
References
[1] http://wiki.octave.org/wiki.pl?CodaTypes
[2] http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.html
[3] http://engineering-matlab.blogspot. in
[4] http://en. literateprograms.org/Category:Programming_language:Matlab
[5] http://wikis.controltheorypro. com/index.php?title=Category:MATLAB
[6] http://www.octnews.org/articles/2932585/image-processing-in-optical-coherence-tomography-u/:Image
[7] http://engineering-matlab.blogspot. in/:Matlab
Saving and loading a MAT-file
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:
file > set path... > add folder...
You could also go to "add folder with subfolders...", if you're adding an entire group ,as you would if you were
installing a toolbox. Then look for and select the folder you want. If you forget to do this and attempt to access a file
that is not part of your defined path list, you will get an 'undefined function' error.
Saving FilesThere are many ways to save to files in MATLAB.
save - saves data to files, *.mat by default
uisave - includes user interface
hgsave - saves figures to files, *.fig by default
diary [filename] - saves all the text input in the command window to a text file.
All of them use the syntax:
save filename.ext
or similar for the other functions. The files are saved in your current directory, as seen on the top of the window. Bydefault the current directory is .../MATLAB/work.
http://engineering-matlab.blogspot.in/:Matlabhttp://www.octnews.org/articles/2932585/image-processing-in-optical-coherence-tomography-u/:Imagehttp://wikis.controltheorypro.com/index.php?title=Category:MATLABhttp://en.literateprograms.org/Category:Programming_language:Matlabhttp://engineering-matlab.blogspot.in/http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.htmlhttp://wiki.octave.org/wiki.pl?CodaTypeshttp://en.wikibooks.org/w/index.php?title=Control_Systemshttp://en.wikibooks.org/w/index.php?title=Signals_and_Systems7/31/2019 MatLab Guide Wikibooks
9/86
Saving and loading a MAT-file 6
Loading Files
Likewise, there are many ways to load files into the workspace. One way is to use the "file" menu. To open a .m file
click "open", whereas to import data from a data file select "import data..." and follow the wizard's instructions.
An alternative way to load a saved .mat file (within a function, for example) is to type:
>> load filename.ext
The file must be in a recognized directory (usually your current directory, but at least one for which the path has
been set).
The data in the .mat file is stored with the same name as the variable originally had when it was saved. To get the
name of this and all other environment variables, type "who".
To open an .m file, you can use file -> open, or type
>>open filename.ext
File Naming Constraints
You can name files whatever you want (usually simpler is better though), with a few exceptions:
MATLAB for Windows retains the file naming constraints set by DOS. The following characters cannot be used
in filenames:
" / : * < > | ?
You're not allowed to use the name of a reserved word as the name of a file. For example, while.m is not a valid
file name because while is one of MATLAB's reserved words.
When you declare an 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.
http://en.wikipedia.org/wiki/Disk_Operating_Systemhttp://en.wikipedia.org/wiki/Microsoft_Windows7/31/2019 MatLab Guide Wikibooks
10/86
Basic Reading and Writing data from a file 7
Basic Reading and Writing data from a file
Reading and Writing from a file: Command Line
Reading and Writing data from/to a .mat file
The quickest means of saving and retrieving data is through the binary .mat file format MATLAB provides. This is
the native format for MATLAB.
Note: This author has had some problems with certain classes not being saved correctly when saving data using
version 7 for use in version 6. Most data items will work just fine. Of particular interest was an issue with
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
The save command is used to save workspace data to a file.
Save all workspace data to the file mySave.mat in the current directory.
>> save('mySave.mat')
>> save(fullfile(pwd, 'mySave.mat'))
Save just the variables myData1 and myData2 to mySave.mat.
>> save('mySave.mat', 'myData1', 'myData2')
Save all myData variables to mySave.mat.
>> save('mySave.mat', 'myData*')
Save all myData variables to a mySave.mat file compatible with version 6 of MATLAB.
>> save('mySave.mat', 'myData*', '-v6')
Save all myData variables to an ASCII file.
>> save('mySave.txt', 'myData*', '-ASCII')
Append new variables to the data file.
>> save('mySave.mat', 'newData*', '-append')
Loading Data
The load command is used to load data from a file into the current workspace.
Load all variables from the file mySave.mat into the current workspace.
>> load('mySave.mat')
>> load(fullfile(pwd, 'mySave.mat'))
Load just the variables myData1 and myData2.
>> load('mySave.mat', 'myData1', 'myData2')
Load all myData variables.
http://en.wikibooks.org/w/index.php?title=User_talk:Spradlighttp://en.wikibooks.org/w/index.php?title=User:Spradlig7/31/2019 MatLab Guide Wikibooks
11/86
Basic Reading and Writing data from a file 8
>> load('mySave.mat', 'myData*')
Get a cell array of variables in saved file.
>> whos('-file', 'mySave.mat')
Reading and Writing from an Excel spreadsheetSince analyzing data is one of the more common motivations for using input output I will start with reading and
writing from a spreadsheet. I cover the command line first since it is often necessary to import the data while an
m-function is being evaluated.
MATLAB makes it easy to read from an Excel spreadsheet. It has the built in command "xlsread". To use thexlsread
function use the syntax:
>>g=xlsread('filename');
This line of code readsfilename.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.
Reading and Writing from and to other text files
If a file is not an excel spreadsheet, it can still be read using "load" function:
>> load newfile.txt
This works only if the text is entirely numerical, without special formatting. Otherwise you get 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.
For reading more general text files, MATLAB does not have a function to do it easily (unless you have excel), but
you can read very general text files (with different delimiters for both cells and text within cells) using the
"textread.m" function in the MATLAB file exchange (do a google search to find it). You can also try to use fscanf if
the formatting is consistent enough (i.e. consistent numbers of spaces, no mixing of strings and numbers in columns,
and so on).
7/31/2019 MatLab Guide Wikibooks
12/86
Basic Reading and Writing data from a file 9
Reading and Writing from a data file: GUI
MATLAB contains a nice GUI application that will guide you through importing data from any recognized data file
(usually .mat, .txt, or .xls on a Windows system). To use it, go to file > import data, and select the file you want.
Then, choose what column separators are present (by selecting the appropriate radio button). Finally, click "next".
MATLAB saves the variable under a name similar to that of the file, but with modifications to make it conform with
MATLAB syntax. Spaces are omitted, plusses and minuses are turned into other characters. To see the name
MATLAB generated (and probably change it) type "who" in the command prompt.
External Resources
ControlTheoryPro.com[5]
MatlabCodes.Webs.com[1]
References
[1] http://matlabcodes.webs.com?title=Category:MATLAB
Boolean and Rational
Introduction
A large number of MATLAB's functions are operations on two types of numbers: rational numbers and boolean
numbers.
Rational numbers are what we usually think of when we think of what a number is. 1, 3, and -4.5 are all rational
numbers. MATLAB stores rational numbers as doubles by default, which is a measure of the number of decimal
places that are stored in each variable and thus of how accurate the values are. Note that MATLAB represents
irrational numbers such as pi with rational approximations, except when using the symbolic math toolbox. See that
section for details.
Boolean numbers are either "TRUE" or "FALSE", represented in MATLAB by a 1 and a 0 respectively. Boolean
variables in MATLAB are actually interchangable with doubles, in that boolean operators can be performed with
arrays of doubles and vice versa. Any non-zero number in this case is considered "TRUE".
Most of the rational operators also work with complex numbers. Complex numbers, however, cannot be
interchanged with boolean values like the real rationals can. See the complex numbers section for details on how to
use them.
Rational Operators on Single Values
MATLAB has all the standard rational operators. It is important to note, however, that Unless told otherwise, all
rational operations are done on entire arrays, and use the matrix definitions. Thus, even though for now we're only
talking about operations on a single value, when we get into arrays, it will be important to distinguish between
matrix and componentwise multiplication, for example.
Add, Subtract, multiply, divide, exponent operators:
%addition
a = 1 + 2
%subtraction
http://matlabcodes.webs.com/?title=Category:MATLABhttp://matlabcodes.webs.com/?title=Category:MATLABhttp://wikis.controltheorypro.com/index.php?title=Category:MATLAB7/31/2019 MatLab Guide Wikibooks
13/86
Boolean and Rational 10
b = 2 - 1
%matrix multiplication
c = a * b
%matrix division (pseudoinverse)
d = a / b
%exponentiation
e = a ^ b
The modulo function returns the remainder when the arguments are divided together, so a modulo b means the
remainder when a is divided by b.
%modulo
remainder = mod(a,b)
All of these functions except for the modulus work for complex numbers as well.
Relational Operators
Equality '==' returns the value "TRUE" (1) if both arguments are equal. This must not be confused with the
assignment operator '=' which assigns a value to a variable.
>>%relational
>>a=5;b=5;
>>a==b
ans = 1
%Assignment
>>a=5;b=3;
>>a=b
a = 3
Note that in the first case, a value of 1 (true) is returned, however for the second case a gets assigned the value of b.
Greater than, less than and greater than or equal to, less than or equal to are given by >, =, >a=3;b=5;
>>a>b
7/31/2019 MatLab Guide Wikibooks
14/86
Boolean and Rational 11
Boolean Operators on Single Values
The boolean operators are & (boolean AND) | (boolean OR) and ~ (boolean NOT /negation). A value of zero means
false, any non-zero value (usually 1) is considered true.
Here's what they do:
>>%boolean AND
>> y = 1 & 0
y = 0
>> y = 1 & 1
y = 1
>>%boolean OR
>> y = 1 | 0
y = 1
>> y = 1 | 1
y = 1
The negation operation in MATLAB is given by the symbol ~, which turns any FALSE values into TRUE and vice
versa:
>> c = (a == b)
c = 1
>>~c
ans = 0
This is necessary because conditionals (IF/SWITCH/TRY) and loops (FOR/WHILE) always look for statements that
are TRUE, so if you want it to do something only when the statement is FALSE you need to use the negation to
change it into a true statement.
The NOT operator has precedence over the AND and OR operators in MATLAB unless the AND or OR statements
are in parenthesis:
>> y = ~1 & 0
y = 0
>> y = ~(1&0)
y = 1
Terminology
MATLAB refers to Booleans as "logicals" and does not use the word "Boolean" in code or documentation.
7/31/2019 MatLab Guide Wikibooks
15/86
Strings 12
Strings
Declaring Strings
Besides numbers, MATLAB can also manipulate strings. They should be enclosed in single quotes:
>> fstring = 'hello'
fstring =
hello
If you would like to include a single quote this is one way to do it:
>> fstring = ''''
fstring =
'
>> fstring = 'you''re'
fstring =
you're
An important thing to remember about strings is that MATLAB treats them as array of characters. To see this, try
executing the following code:
>> fstring = 'hello';
>> class(fstring)
ans = char
Therefore, many of the array manipulation functions will work the same with these arrays as any other, such as the
'size' function, transpose, and so on. You can also access specific parts of it by using standard indexing syntax.
Attempting to perform arithmetic operations on character arrays converts them into doubles.
>> fstring2 = 'world';
>> fstring + fstring2
ans = 223 212 222 216 211
These numbers come from the standard numbers for each character in the array. These values are obtained by using
the 'double' function to turn the array into an array of doubles.
>> double(fstring)
ans = 104 101 108 108 111
The 'char' function can turn an array of integer-valued doubles back into characters. Attempting to turn a decimal
into a character causes MATLAB to round down:
>> char(104)
ans = h
>> char(104.6)
ans = h
Since the MATLAB strings are treated as character arrays, they have some special functions if you wish to compare
the entire string at once rather than just its components:
findstr(bigstring, smallstring) looks to see if a small string is contained in a bigger string, and if it is returns theindex of where the smaller string starts. Otherwise it returns [].
7/31/2019 MatLab Guide Wikibooks
16/86
Strings 13
strrep(string1, replaced, replacement) replaces all instances ofreplacedin string1 with replacement
Displaying values of string variables
If all you want to do is display the value of a string, you can omit the semicolon as is standard in MATLAB.
If you want to display a string in the command window in combination with other text, one way is to use array
notation combined with either the 'display' or the 'disp' function:
>> fstring = 'hello';
>> display( [ fstring 'world'] )
helloworld
MATLAB doesn't put the space in between the two strings. If you want one there you must put it in yourself.
This syntax is also used to concatenate two or more strings into one variable, which allows insertion of unusual
characters into strings:
>> fstring = ['you' char(39) 're']
fstring = you're
Any other function that returns a string can also be used in the array.
You can also use the "strcat" function to concatenate strings, which does the same thing as above when you use two
strings, but it is especially useful if you are using a cell array of strings because it lets you concatenate the same thing
to all of the strings at once. Unfortunately you can't use it to add white space (strcat discards what MATLAB
considers extraneous whitespace). Here's the syntax for this use.
>> strCell = {'A', 'B'};
>> strcat(strCell, '_');
ans =
A_
B_
Finally, although MATLAB doesn't have a printf function you can do essentially the same thing by using 1 as your
file identifier in the fprintffunction. The format identifiers are essentially the same as they are in C.
>> X = 9.2
>> fprintf(1, '%1.3f\n', X);
9.200
The "9.200" is printed to the screen. fprintf is nice compared to display because you don't have to call num2str on all
of the numbers in a string - just use the appropriate format identifer in the place you want it.
>> X = 9.2
>> fprintf(1, 'The value of X is %1.3f meters per second \n', X);
The value of X is 9.200 meters per second
7/31/2019 MatLab Guide Wikibooks
17/86
Strings 14
Cell arrays of strings
In many applications (particularly those where you are parsing text files, reading excel sheets with text, etc.) you will
encounter cell arrays of strings.
You can use the function "iscellstr" to tell if all of the elements in a given cell array are strings or not.
>> notStrCell = {'AA', []};
>> iscellstr(notStrCell)
ans = 0
This is useful since functions that work with cell arrays of strings will fail if provided with something that's not a cell
array of strings. In particular, they all fail if any elements of the provided cell array are the empty array ( [] ) which is
somewhat frustrating if the provided text file contains empty cells. You must catch this exception before calling
cellstr manipulation functions.
Searching a cell array of strings can be done with the "strmatch", "strfind", and "regexp" functions. Strmatch looks
for a string within a cell array of strings whose first characters exactly match the string you pass to it, and returns the
index of all strings in the array for which it found a match. If you give it the 'exact' option, it will only return the
indexes of elements that are exactly the same as what you passed. For example:
>> strCell = {'Aa', 'AA'};
>> strmatch('A', strCell);
ans = 1, 2
>> strmatch('A', strCell, 'exact');
ans = []
>> strmatch('Aa', strCell, 'exact');
ans = 1
Strfind looks for a specific string within a cell array of strings, but it tries to find it in any part of each string. For
each element x of the given cell array of strings, it will return an empty array if there is no match found in x and the
starting index (remember, strings are arrays of characters) of all matches in x if a match to the query is found.
>> strCell = {'Aa', 'AA'};
>> strfind(strCell, 'A');
ans = % answer is a cell array with two elements (same size as
strCell):
1 % Index of the beginning of string "A" in the first cell
1 2 % Index of each instance of the beginning of string "A" in
the second cell
>> strfind(strCell, 'a');
ans =
2
[] % 'a' is not found
The "cellfun" / "isempty" combination is very useful for identifying cases where the string was or was not found.
You can use the find function in combination with these two functions to return the index of all the cells in which the
query string was found.
>> strCell = {'Aa', 'AA'};
>> idxCell = strfind(strCell, 'a');
>> isFound = ~cellfun('isempty', idxCell); % Returns "0" if idxCell is
empty and a "1" otherwise
7/31/2019 MatLab Guide Wikibooks
18/86
Strings 15
>> foundIdx = find(isFound)
foundIdx = 2
The strfind function also has some other options, such as the option to only return the index of the first or last match.
See the documentation for details.
The regexp function works the same way as strfind but instead of looking for strings literally, it tries to find matches
within the cell array of strings using regular expressions. Regular expressions are a powerful way to match patterns
within strings (not just specific strings within strings). Entire books have been written about regular expressions, so
they cannot be covered in as much detail here. However, some good resources online include regular-expresions.info[1]
and the MATLAB documentation for the matlab-specific syntax. Note that MATLAB implements some, but not
all, of the extended regular expressions available in other languages such as Perl.
Unfortunately, MATLAB does not innately have functions to do common string operations in some other languages
such as string splitting. However, it is quite possible to find many of these functions in a google search.
Comparing strings
Unlike with rational arrays, strings will not be compared correctly with the relational operator, because this will treat
the string as an array of characters. To get the comparison you probably intended, use the strcmp function as follows:
>> string1 = 'a';
>> strcmp(string1, 'a')
ans = 1
>> strcmp(string1, 'A')
ans = 0
Note that MATLAB strings are case sensitive so that 'a' and 'A' are not the same. In addition the strcmp function
does notdiscard whitespace:
>> strcmp(string1, ' a')
ans = 0
The strings must be exactly the same in every respect.
If the inputs are numeric arrays then the strcmp function will return 0 even if the values are the same. Thus it's only
useful for strings. Use the == operator for numeric values.
>> strcmp(1,1)
ans = 0.
References
[1] http://www.regular-expressions.info/
http://www.regular-expressions.info/http://www.regular-expressions.info/7/31/2019 MatLab Guide Wikibooks
19/86
Portable Functions 16
Portable Functions
This section discusses anonymous functions and function handles. Both of these are portable in that rather than
having to write an equation multiple times in a program, you can just define it once and then call it whenever you
want to use it. In addition, function handles in particular allow you to pass an equation to another function for direct
evaluation as needed. Anonymous functions are useful for command-line evaluation or for multiple evaluations in
the same m-file.
Anonymous functions
An anonymous function can be created at the command or in a script:
>>f = @(x) 2*x^2-3*x+4;
>>f(3)
ans = 13
To make an anonymous function of multiple variables, use a comma-separated list to declare the variables:
>>f = @(x,y) 2*x*y;
>>f(2,2)
ans = 8
It is possible to make an array of anonymous functions in MATLAB 7.1 but this will become outdated soon so using
this construct in a distributed program is not recommended.
To pass anonymous functions to other functions, just use the name of the anonymous function in your call:
>> f = @(t,x) x;
>> ode45(f, [0:15],1)
Function Handles
A function handle passes an m-file function into another function. This of course lets you have more control over
what's passed there, and makes your program more general as it lets you pass any m-file (as long as it meets other
requirements like having the right number of input arguments and so on). The functionality is similar to that of
function pointers in C++.
To pass an m-file to a function, you must first write the m-file, say something like this:
function xprime = f(t,x)
xprime = x;
Save it as myfunc.m. To pass this to another function, say an ODE integrator, use the @ symbol as follows:
>> ode45(@myfunc, [0:15], 1)
One advantage of using function handles over anonymous functions is that you can evaluate more than one equation
in the m-file, thus allowing you to do things like solve systems of ODEs rather than only one. Anonymous functions
limit you to one equation.
7/31/2019 MatLab Guide Wikibooks
20/86
Portable Functions 17
How to write a function that accepts a function handle
You can also write your own functions that accept function handles. Simply define them as variables in your header,
and then call them as if they were functions:
% myadd adds two variables together
function result = myfunc(func, a, b);
result = func(a, b);
[in a separate m-file]
function sum = myadd(a, b)
sum = a+b;
The command you send to myfunc looks like this:
>> result = myfunc(@myadd, 1, 2);
result = 3
Complex Numbers
Declaring a complex number in MATLAB
Complex numbers in MATLAB are doubles with a real part and an imaginary part. The imaginary part is declared by
using the 'i' or 'j' character. For example, to declare a variable as '1 + i' just type:
>> compnum = 1 + i
compnum = 1.000 + 1.000i
>> compnum = 1 + j
compnum = 1.000 + 1.000i
Note that if you use j MATLAB still displays i on the screen.
Since i is used as the complex number indicator it is not recommended to use it as a variable, since it will assume it's
a variable if given a choice.
>> i = 3; %bad idea
>> a = 1 + i
a = 4
However, since implicit multiplication is not normally allowed in MATLAB, it is still possible to declare a complex
number like this:
>> i = 3;
>> a = 1i + 1
a = 1.000 + 1.000i
It's best still not to declare i as a variable, but if you already have a long program with i as a variable and need to use
complex numbers this is probably the best way to get around it.
If you want to do arithmetic operations with complex numbers make sure you put the whole number in parenthesis,
or else it likely will not give the intended results.
7/31/2019 MatLab Guide Wikibooks
21/86
Complex Numbers 18
Arithmetic operations that create complex numbers
There are several operations that create complex numbers in MATLAB. One of them is taking an even root of a
negative number, by definition.
>> (-1)^0.5
ans = 0.000 + 1.000i
>> (-3)^0.25
ans = 0.9306 + 0.9306i
As a consequence of the Euler formula, taking the logarithm of a negative number also results in imaginary answers.
>> log(-1)
ans = 0 + 3.1416i
In addition, the roots of functions found with the 'roots' function (for polynomials) or some other rootfinding
function will often return complex answers.
MATLAB functions to manipulate complex values
First of all, it is helpful to tell whether a given matrix is real or complex when programming, since certain operations
can only be done on real numbers. Since complex numbers don't have their own class, MATLAB comes with
another function called 'isreal' to determine if a given matrix is real or not. It returns 0 if any of the inputs are
complex.
>> A = [1 + i, 3];
>> isreal(A)
ans = 0
>> isreal(A(2))
ans = 1
Notice that it is possible to have real and complex numbers in the same array, since both are of class double. The
function is set up this way so that you can use this as part of a conditional, so that a block only is executed if all
elements of array A are real.
To extract just the real part of a complex variable use the 'real' function. To extract just the complex part use the
'imag' function.
>> real(A)
ans = 1 3
>> imag(A)
ans = 1 0
One thing you may need to do is perform an operation on the real values of an array but not the complex values.
MATLAB does not have a function to directly do this, but the following pair of commands lets you put only the real
values into another array:
>> RealIndex = (imag(A) == 0); %if imaginary part is zero then the number is real)
>> RealOnly = A(RealIndex)
RealOnly = 3
7/31/2019 MatLab Guide Wikibooks
22/86
Arrays 19
Arrays
Introduction to Arrays
Arrays are the fundamental data type of MATLAB. Indeed, the former data types presented here, strings and
number, are particular cases of arrays. As in many traditional languages, arrays in MATLAB are a collection of
several values of the same type (by default, the type is equivalent to the C type double on the same architecture. On
x86 and powerpc, it is a floating point value of 64 bits). They are indexed through the use of a single integer or, to
get more than one value, an array of integers..
Declaring Arrays
Row and Column Arrays
A simple way to create a row array is to give a comma separated list of values inside brackets:
>> array = [0, 1, 4, 5]array =
0 1 4 5
The commas can be omitted for a row array because MATLAB will assume you want a row array if you don't give it
any separators. However, the commas make it easier to read and can help with larger arrays. The commas indicate
that the array will be a horizontal array.
To make a column array you can use semicolons to separate the values.
>> column = [1; 2; 3]
column =
1
2
3
All elements of an array must be the same data type, so for example you cannot put a function handle and a double in
the same array.
Declaring multi-dimensional arrays
Arrays can be multi-dimensional. To create a 2 dimensional array (a matrix in Linear Algebra terms), we have to
give a list of comma separated values, and each row should be separated by a semi colon:
>> matrix = [1, 2, 3; 4, 5, 6]
matrix =
1 2 3
4 5 6
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:
>> matrix = [1, 2, 3; 4, 5]
??? Error using ==> vertcatAll rows in the bracketed expression must have the same
number of columns.
7/31/2019 MatLab Guide Wikibooks
23/86
Arrays 20
Properties of MATLAB arrays and matrices
Contrary to low level languages such as C, an array in MATLAB is a more high level type of data: it contains
various information about its size, its data type, and so on.
>> array = [0,1,4,5];
>> length(array)
ans = 4
>> class(array)
ans = double
The number of rows and columns of the matrix can be known through the 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:
>> matrix = [1, 2, 3; 4, 5, 6];
>> size(matrix)
ans =
2 3
The goal of MATLAB arrays is to have a type similar to mathematical vectors and matrices. As such, row and
column arrays are not equivalent. 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
Why Use Arrays?
A major advantage of using arrays and matrices is that it lets you avoid using loops to perform the same operation on
multiple elements of the array. For example, suppose you wanted to add 3 to each element of the array [1,2,3]. If
MATLAB didn't use arrays you would have to do this using a FOR loop:
>> array = [1,2,3];
>> for ii = 1:3
array(ii) = array(ii) + 3;
>> end
>> array
array = [4,5,6]
Doing this is not efficient in MATLAB, and it will make your programs run very slowly. Instead, you can create
another array of 3s and add the two arrays directly. MATLAB automatically separates the elements:
7/31/2019 MatLab Guide Wikibooks
24/86
Arrays 21
>> array = [1,2,3];
>> arrayofthrees = [3,3,3];
>> array = array + arrayofthrees
array = [4,5,6];
If all you are doing is adding a constant, you can also omit the declaration of 'arrayofthrees', as MATLAB will
assume that the constant will be added to all elements of the array. This is very useful, for example if you use an
array with variable size:
>> array = [1,2,3];
>> array + 3
ans = [4,5,6]
The same rule applies to scalar multiplication.
See Introduction to array operations for more information on the operations MATLAB can perform on arrays.
Arrays are a fundamental principle of MATLAB, and almost everything in MATLAB is done through a massive use
of arrays. To have a deeper explanation of arrays and their operations, see Arrays and matrices.
Introduction to array operations
Introduction to array operations
As arrays are the basic data structure in MATLAB, it is important to understand how to use them effectively. See the
previous section for that.
Arrays in MATLAB obey the same rule as their mathematical counterpart: by default, the matrix definitions of
operations are used, unless a special operator called the dot operator is applied.Because arrays operations are so similar to the equivalent mathematical operations, a basic knowledge of linear
algebra is mandatory to use matlab effectively. However, we won't be as precise as in mathematics when using the
terms vector and matrix. In MATLAB, both are arrays of doubles (thus being a matrix in the real mathematical
meaning), and MATLAB considers vectors as a matrices with only one row or only one column. However, there are
special functions just for vectors; see the vector module for an explanation of how to use these.
Basics
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
7/31/2019 MatLab Guide Wikibooks
25/86
Introduction to array operations 22
>> [1; 2; 3]
ans =
1
2
3
If a blankspace is used to separate elements, the default separator is comma, thus making the vector a row vector.
Logically, inputting a matrix is done by using a comma separated list of column vectors, or a semicolon separated
list of row vectors:
>> [1, 2, 3; 4, 5, 6]
ans =
1 2 34 5 6
Variable assignment
To reuse an array in subsequent operations, one should assign the array to a variable. Variable assignment is done
through the equal symbol:
>> a = [1, 2, 3]
a =
1 2 3
Notice that instead of ans =, the name of the variable is displayed by matlab. If you forget to assign the last statement
to a variable, the variable ans always point to the last non assigned:
>> [1, 2, 3]
ans =
1 2 3
>> a = ans
a =
1 2 3
But:
>> [1, 2, 3]
ans =
1 2 3
7/31/2019 MatLab Guide Wikibooks
26/86
Introduction to array operations 23
>> b = [4, 5, 6]
b =
4 5 6
>> a = ans
a =
1 2 3
I.e. ans is really the last non assigned result, and not the result of the last statement.
As it is the case for most interpreted languages, you do not need to declare a variable before using it, and reusing a
variable name in an assignment will overwrite the previous content.
To avoid cluttering the command line of matlab, you can postfix any command with a semicolon:
>> a = [1, 2, 3];
Accessing elements of a matrix
Now that you know how to define a simple array, you should know how to access its elements. Accessing the
content of an array is done through the operator (), with the index inside the parenthesis; the indexing of the first
element is 1:
>> a = [1, 2, 3];
>> a(1)
ans =
1
>> a(3)
ans =
3
Accessing an element outside the bounds will result in an error:
>> a(5)
??? Index exceeds matrix dimensions.
To access a single matrix element, you can use the (i,j) subscript, where i is the index in the row, and j in the column:
>> a= [1, 2; 3, 4];
>> a(1, 2)
ans =
2
7/31/2019 MatLab Guide Wikibooks
27/86
Introduction to array operations 24
>> a(2, 1)
ans =
3
You can also access a matrix element through a unique index; in this case, the order is column major, meaning you
first go through all elements of the first column, then the 2d column, etc... The column major mode is the same than
in Fortran, and the contrary of the order in the C language.
>> a = [1, 2, 3; 4, 5, 6];
>> a(3)
ans =
2
It is also possible to access blocks of matrices using the colon (:) operator. This operator is like a wildcard; it tells
MATLAB that you want all elements of a given dimension or with indices between two given values. For example,
say you want to access the entire first row of matrix a above, but not the second row. Then you can write:
>> a = [1, 2, 3; 4, 5, 6];
>> a(1,:) %row 1, every column
ans =
1 2 3
Now say you only want the first two elements in the first row. To do this, use the following syntax:
>> a = [1, 2, 3; 4, 5, 6];
>> a(1, 1:2)
ans =
1 2
The syntax a(:) changes a into a column vector (column major):
>> a = [1, 2, 3; 4, 5, 6]
>> a(:)
ans =
14
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 =
7/31/2019 MatLab Guide Wikibooks
28/86
Introduction to array operations 25
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 findfunction to find the indices of all numbers between 2 and 4 in the array, andthen address the array with those indices:
>> a = [1.1, 2.1, 3.2, 4.5];
>> INDICES = find(a >= 2 & a > a(INDICES)
ans =
2.1 3.2
This does not work in Matlab 2006b
The second method is to use logical addressing, which first changes a into a logical array, with value 1 if the logical
expression is true and 0 if it is false. It then finds and returns all values in the a which are true. The syntax for this is
as follows:
>> a = [1.1, 2.1, 3.2, 4.5];
>> a(a >= 2 & a > [1, 2, 3] - [1, 2, 1]
ans =
0 0 2
The multiplication by a scalar also works as expected:
>> 2 * [1, 2, 3]
ans =
[2, 4, 6]
Multiplication and division are more problematic: multiplying two vectors in does not make sense. It makes
sense only in the matrix context. Using the symbol * in matlab computes the matrix product, which is only defined
when the number of columns of the left operand matches the number of rows of the right operand:
>> a = [1, 2; 3, 4];
>> a * a
7/31/2019 MatLab Guide Wikibooks
29/86
Introduction to array operations 26
ans =
7 10
15 22
>> a = [1, 2, 3]; b = [1; 2; 3];>> a * a
??? Error using ==> *
Inner matrix dimensions must agree.
>> a * b
ans =
14
Using the division symbol / has even more constraints, as it imposes the right operand to be invertible (see
Wikipedia:Invertible matrix). For square matrices, is equivalent to . For example :
>> a = [1, 2; 3, 4]; b = [1, 2; 1, 2]
>> b / a
ans =
1 0
1 0
>> a / b
Warning: Matrix is singular to working precision.
ans =
Inf Inf
Inf Inf
If you desire to multiply or divide two matrices or vectors componentwise, or to raise all components of one matrix
to the same power, rather than using matrix definitions of these operators, you can use the dot (.) operator. The two
matrices must have the same dimensions. For example, for multiplication,
>> a = [1, 2, 3];
>> b = [0, 1, 2];
>> a .* b
ans =
0 2 6
The other two componentwise operators are ./ and .^.
As matlab is a numerical computing language, you should keep in mind that a matrix which is theoretically invertible
may lead to precision problems and thus giving imprecise results or even totally wrong results. The message above
"matrix is singular to working precision" should appear in those cases, meaning the results cannot be trusted.
http://en.wikipedia.org/wiki/Invertible_matrix7/31/2019 MatLab Guide Wikibooks
30/86
Introduction to array operations 27
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.
Boolean Operators on Arrays
The same boolean operators that can be used for point values can also be used to compare arrays. To do this,
MATLAB compares the elements componentwise and returns them in a logical array of the same size as the twoarrays being compared. The two arrays must have the same size. For example,
>> A = [2,4], B = [1,5];
>> A < B
ans =
[0 1]
You must be careful when using comparisons between arrays as loop conditions, since they clearly do not return
single values and therefore can cause ambiguous results. The loop condition should be reducable to a single boolean
value, T or F, not an array. Two common ways of doing this are the "any" and the "all" functions. A function callany(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.
Solving Linear Systems
To solve a linear system in the form Ax = b use the "\" operator.
Example:
>>A = [4 5 ; 2 8];
b = [23 28]';
x = A\b
x =
2
3
http://en.wikipedia.org/wiki/Pseudoinverse7/31/2019 MatLab Guide Wikibooks
31/86
Struct Arrays 28
Struct Arrays
Introduction to Structures
MATLAB provides a means for structure data elements. Structures are created and accessed in a manner familiar for
those accustomed to programming in C.
MATLAB has multiple ways of defining and accessing structure fields. See Declaring Structures for more details.
Note: Structure field names must begin with a letter, and are case-sensitive. The rest of the name may contain letters,
numerals, and underscore characters. Use the namelengthmax function to determine the maximum length of a field
name.
Declaring Structures
Structures can be declared using the struct command.
>> a = struct('b', 0, 'c', 'test')
a =
b: 0
c: 'test'
In MATLAB, variables do not require explicit declaration before their use. As a result structures can be declared
with the '.' operator.
>> b.c = 'test'
b =
b: 0
c: 'test'
Structures can be declared as needed and so can the fields.
Arrays of Structures
Structures can also be arrays. Below is an example
>> a = struct('b', 0, 'c', 'test'); % Create structure
>> a(2).b = 1; % Turn it into an array by creating another element
>> a(2).c = 'testing'
a =
1x2 struct array with fields:
b
c
>> a(1) % Initial structure
ans =
b: 0
c: 'test'
>> a(2) % The second element
ans =
b: 1
c: 'testing'
7/31/2019 MatLab Guide Wikibooks
32/86
Struct Arrays 29
Accessing Fields
When the field name is known the field value can be accessed directly.
>> a.c
ans =
test
ans =
testing
In some cases you may need to access the field dynamically which can be done as follows.
>> str = 'c';
>> a(1).(str)
ans =
test
>> a(1).c
ans =
test
Accessing Array Elements
Any given element in a structure array can be accessed through an array index like this
>> a(1).c
ans =
test
To access all elements in a structure array use the syntax {structure.field}. In order to get all values in a vector or
array use square brackets ([]) as seen below.
>> [a.('c')]
ans =
testtesting
>> [a.('b')]
ans =
0 1
Or you can put them all into a cell array (rather than concatenating them) like this:
>> {a.('c')}
ans = {'test', 'testing'}
External Resources
ControlTheoryPro.com[1]
References
[1] http://wikis.controltheorypro. com/index.php?title=Structures
http://wikis.controltheorypro.com/index.php?title=Structureshttp://wikis.controltheorypro.com/index.php?title=Structures7/31/2019 MatLab Guide Wikibooks
33/86
Cell Arrays 30
Cell Arrays
Introduction
Cell arrays are created just like regular arrays except that curly brackets are used instead of square brackets.
array = [1, 2, 3; 4, 5, 6];
cell_array = {1, 2, 3; 4, 5, 6};
The array variable is 1 array with 2 rows and 3 columns. Each element is a scalar. The cell_array variable is
essentially an array of arrays. In this case the cell_array variable is made up of 6 arrays with 1 scalar element in each
of the 6 arrays.
Cell arrays have fewer limitations than regular arrays. The regular array, defined by the square brackets, can hold
numbers or strings but if it holds strings in each element all the strings must be the same length. Also, if 1 element of
an array is a string all elements must be a string. Cell arrays have neither of these limitations.
cell_array = {1, 2, 'a', 'abc'; rand(3, 2), magic(3), eye(3), 'junk'}cell_array =
[ 1] [ 2] 'a' 'abc'
[3x2 double] [3x3 double] [3x3 double] 'junk'
With the lack of limitations/rules for the content of a cell array comes complications. These cell arrays are very
powerful tools but take a lot of time to get used to because each element can be almost anything.
Cell arrays can also be dynamically resized--a key feature in more advanced data structures. For example, one can
create a queue data structure using the commands:
cell_array{end+1}='a';
cell_array{end+1}='b';
... etc.
Once can pop an element from the front of the queue using the commands:
cell_array(1)=[]; % remove first element - resize
cell_array(1)=[]; % remove first element - resize
... etc.
External Links
ControlTheoryPro.com[1]
References
[1] http://wikis.controltheorypro. com/index.php?title=Cell_Arrays
http://wikis.controltheorypro.com/index.php?title=Cell_Arrayshttp://wikis.controltheorypro.com/index.php?title=Cell_Arrays7/31/2019 MatLab Guide Wikibooks
34/86
Sparse Matrices 31
Sparse Matrices
A Sparse Matrix is a matrix that mostly contains zeros. In Matlab, sparse matrices contrast regular ones in the way
they are stored, such that memory is used more efficiently for matrices that are sparse.
A regular matrix can be converted to a sparse matrix using
>> S = sparse(A); % Create sparse representation of A
Sparse matrices are very common in engineering purposes. This is useful for manipulation as most of the matrix has
a value of 0.
Graphics
2D Graphics
Plot
Plots a function in Cartesian Coordinates, x and y.
Example:
x=0:0.1:2; % creates a line vector from 0 to 2
fx=(x+2)./x.^2; % creates fx
plot(x,fx,'-ok') % plots 2d graphics of the function fx
To plot 2 or more graphs in one Figure, then simply append the second (x,y) pair to the first:
>>>x1 = [1,2,3,4]
>>>y1 = [1,2,3,4]
>>>y2 = [4,3,2,1]
>>>plot(x1,y1,x1,y2)
This will plot y1 and y2 on the same x-axis in the output.
Polar Plot
Plots a function using and r()
t = 0:.01:2*pi;
polar(t,sin(2*t).^2)
3D Graphics
plot3
The "plot3" command is very helpful and easy to see three dimensional images. It follows the same syntax as the
"plot" command. If you search the MATlab help (not at the command prompt. Go to the HELP tab at the top of the
main bar then type plot3 in the search) you will find all the instruction you need.
Example:
l=[-98.0556 ; 1187.074];
f=[ -33.5448 ; -240.402];
7/31/2019 MatLab Guide Wikibooks
35/86
Graphics 32
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
Creates a 2D plot of a 3D projection, using vectors x and y, and a matrix z. If x is n elements long, and y is m
elements long, z must be an m by n matrix.
Example:
x=[0:pi/90:2*pi]';
y=x';
z=sin(x*y);
contour(x,y,z);
Contourf
Same as contour, but fills color between contour lines
Surface
Basically the same as mesh
7/31/2019 MatLab Guide Wikibooks
36/86
Annotate 33
Annotate
MATLAB offers incomparable control over the way you can add details to your plot. From inserting text at the right
positions to labelling the axes, MATLAB from the command line offers you an easy way to create publication style
graphics. With support for Encapsulated postscript and Illustrator output. Complex figures with several axes and
conveying large amounts of information can be created.
Concept of a handle
Most operations on figures generate objects with a set of properties. Users familiar with Object oriented
programming would realize that the functions and the data are encapsulated into the object. A typical figure would
contain at least half a dozen objects. These objects are called handles. A very tacky analogy would be like handles to
several different refrigerators with several different contents. To provide an intuitive feel. I have listed out the
properties from a text handle.
Finding a handleVarious commands provide required handles, for example:
h = gcf; % Get current figure
h = gca; % Get current axis
Examples
Axis Label
xlabel labels the x-axis of the current plot
>>xlabel('string')
You can display text on two lines or insert the value of variables
>>xlabel({['First Line or line n ',int2str(a)],['Second Line or line n',int2str(b)]})
ylabel labels the y-axis of the current plot. It works in same way of xlabel but the output is vertical in 2D plots.
Documenting a Maximum Value
% Previous code set the x value of the peak data point into x_peak
plot(lags(1:1000:end),abs_cs(1:1000:end));
ptitle = 'UUT and Source Correlation Score Magnitude';
xlabel('Lag');
ylabel('Correlation Magnitude');
title(ptitle);
yloc = max(get(gca,'YLim')); % Put at top of plot
text(lags(x_peak),yloc,[' \leftarrow ' num2str(x_peak) 'ns']);
lstr{1} = sprintf(' Test %d', TESTNUM);
lstr{2} = sprintf(' Unit %d%s', UNITNUM, comparestr);
text(lags(1),mean(get(gca,'YLim')),lstr);
7/31/2019 MatLab Guide Wikibooks
37/86
Scripts 34
Scripts
M-files
There are 2 types of m-file
Scripts
Functions
Scripts are a type of m-file that runs in the current workspace. So if you call a script from the command line (base
workspace) the script will use and manipulate the variables of the base workspace. This can get very messy and lead
to all sorts of strange errors when loops are involved and the coder is lazy about about naming their loop variables
(i.e. for i = 1:10, if every loop uses i, j, or k then it's likely that any script called from a loop will alter the loop
variable).
Functions are wholly contained in themselves. They possess their own workspace keeping workspaces separate. This
means that all variables necessary for a particular function must be passed or defined in some way. This can get
tedious for complex algorithms requiring lots of variables. However, any manipulations of variables are discardedwhen 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).
Requirements for a function
Custom functions follow this syntax in their most basic form:
function [output1, output2, ...]= function_name(input_arg1,input_arg2)
statements
return;
In current versions of MATLAB the return; line is not required. Thefunction_name can be anything you like but it is
best if the m-file name isfunction_name.m. Calling the function from the command line or another m-file is done byinvoking 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.
Typically output arguments are initialized to empty ([]) or 0 or -1 or something equivalent for other data types. The
reason is that if the function encounters an error you've anticipated then the function can return (via the return
command) with those default values. If the initialization value is an invalid value then it can easily be checked by the
calling function for any errors which may not throw a MATLAB error.
7/31/2019 MatLab Guide Wikibooks
38/86
Scripts 35
Path
In order to invoke a function that function's m-file must be in the current path. There is a default path that can be
setup through the File menu or the addpath command. The order of the path is important as MATLAB searches the
path in order and stops searching after it finds the 1st
instance of that m-file name.
The current path is
the current directory (which can be seen at the top of the MATLAB window or by typingpwdat the command
prompt
the default path
Note that MATLAB will always search the current directory before searching any of the rest of the path.
nargin & nargout
The nargin and nargoutcommands are only valid inside functions since scripts are not passed any arguments. The
nargin command returns the number of passed input arguments. This is useful in conjunction with nargchk
nargchk(min, max, nargin)
where min is the minimum number of arguments necesary for the function to operate and max is the maximum
number of valid input arguments.
The nargoutcommand 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 nargoutcommand. If the caller isn't
saving the secondary output arguments then they do not need to be calculated.
varargin & varargout
When using MATLAB objects and functions they often allow the user to set properties. The functions and objects
come with default values for these properties but the user is allowed to override these defaults. This is accomplished
through the use of varargin. varargin is a cell array that is usually parsed where varargin{i} is a property and
varargin{i+1} is the value the user wishes for that property. The parsing is done with aforor while loop and a switch
statement.
function [out] = myFunc(in, varargin)
The varargoutoutput 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[1]
function [s,varargout] = mysize(x)nout = max(nargout,1)-1;
s = size(x);
for k=1:nout, varargout(k) = {s(k)}; end
returns the size vector and, optionally, individual sizes. So
[s,rows,cols] = mysize(rand(4,5));
returns s = [4 5], rows = 4, cols = 5.
http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/varargout.html&http://www.google.com/search?sourceid=navclient&ie=UTF-8&rlz=1T4GFRD_enUS257US258&q=varargout+MATLAB7/31/2019 MatLab Guide Wikibooks
39/86
Scripts 36
Useful syntax guidelines
Placing the semicolon symbol after every line tells the compiler not to place that line of code in the command
prompt and then execute. This can make your programs run a lot faster. Also, placing a semicolon after every line
helps with the debugging process.
syms x y z;
w=[x y z];
e=[1 2 3];
t=jacobian(e,w);
Placing comments in your code can help other people (and yourself) understand your code as it gets more complex.
syms x y z; %syms command makes x y and z symbolic
w=[x y z];
e=[1 2 3];
t=jacobian(e,w);
Comments can also Identify who wrote the code and when they wrote it.
%Some code writer
%mm/dd/yyyy
See the 'comments' section for more details on this.
External Links
Large parts of this page come from the ControlTheoryPro.com page on M-files[2]
, Scripts[3]
, and Functions[4]
.
References[1] http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/varargout. html&http://
www.google.com/search?sourceid=navclient&ie=UTF-8&rlz=1T4GFRD_enUS257US258&q=varargout+ MATLAB
[2] http://wikis.controltheorypro. com/index.php?title=M-files
[3] http://wikis.controltheorypro. com/index.php?title=MATLAB_Scripts
[4] http://wikis.controltheorypro. com/index.php?title=MATLAB_Functions
http://wikis.controltheorypro.com/index.php?title=MATLAB_Functionshttp://wikis.controltheorypro.com/index.php?title=MATLAB_Scriptshttp://wikis.controltheorypro.com/index.php?title=M-fileshttp://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/varargout.html&http://www.google.com/search?sourceid=navclient&ie=UTF-8&rlz=1T4GFRD_enUS257US258&q=varargout+MATLABhttp://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/varargout.html&http://www.google.com/search?sourceid=navclient&ie=UTF-8&rlz=1T4GFRD_enUS257US258&q=varargout+MATLABhttp://wikis.controltheorypro.com/index.php?title=MATLAB_Functionshttp://wikis.controltheorypro.com/index.php?title=MATLAB_Scriptshttp://wikis.controltheorypro.com/index.php?title=M-files7/31/2019 MatLab Guide Wikibooks
40/86
Comments 37
Comments
Placing comments
Comment lines begin with the character '%', and anything after a '%' character is ignored by the interpreter. The %
character itself only tells the interpreter to ignore the remainder of the same line.
In the MATLAB Editor, commented areas are printed in green by default, so they should be easy to identify. There
are two useful keyboard shortcuts for adding and removing chunks of comments. Select the code you wish to
comment or uncomment, and then press Ctrl-R to ( -/ for Mac) place one '%' symbol at the beginning of each line
and Ctrl-T ( -T for Mac) to do the opposite.
Common uses
Comments are useful for explaining what function a certain piece of code performs especially if the code relies on
implicit or subtle assumptions or otherwise perform subtle actions. Doing this is a good idea both for yourself and
for others who try to read your code. For example,
% Calculate average velocity, assuming acceleration is constant
% and a frictionless environment.
force = mass * acceleration
It is common and highly recommended to include as the first lines of text a block of comments explaining what an M
file does and how to use it. MATLAB will output the comments leading up to the function definition or the first
block of comments inside a function definition when you type:
>> help functionname
All of MATLAB's own functions written in MATLAB are documented this way as well.
Comments can also be used to identify authors, references, licenses, and so on. Such text is often found at the end of
an M file though also can be found at the beginning. Finally, comments can be used to aid in debugging, as
explained in Debugging M Files.
http://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Debugging_M_Files7/31/2019 MatLab Guide Wikibooks
41/86
Entering data at the command line 38
Entering data at the command line
The input() function lets your scripts process data entered at the command line. All input is converted into a
numerical value or array. The argument for the input() function is the message or prompt you want it to display.
Inputting strings require an additional 's' argument. Example:
%test.m
%let's ask a user for x
x = input('Please enter a value for x:')
Then running the script would produce the output:
Please enter a value for x:3
x = 3
>>
Loops and Branches
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.
7/31/2019 MatLab Guide Wikibooks
42/86
Error Messages 39
Error Messages
As far as I've seen there is little help out there to help people decipher MATLAB's error messages. Most of the
syntax errors are not difficult to fix once you know what is causing them so this is intended to be a guide to
identifying and fixing errors in MATLAB code.
Warnings are also shown here as these often lead to errors later.
Arithmetic errors
Usually these are self-explanatory. As a reminder, here are some common functions that cannot be performed and
what MATLAB returns (along with a warning for each one):
a/0 = Inf if a > 0, -Inf if a < 0, and NaN if a = 0.
log(0) = -Inf
MATLAB defines 0^0 to be 1.
NaN will very often result in errors or useless results unless measures are taken to avoid propogating them.
???Error using ==> minus
Matrix dimensions must agree.
So check the dimensions of all the terms in your expression. Often it is an indexing mistake that causes the terms to
be of different size. If you are using power function you might add a single dot after the parameter. i.e. y=x.^2
instead of y=x^2
Matrix multiplication requires the number ofcolumns in the first matrix to equal the number ofrows in the second.
Otherwise, you get the message:
??? Error using ==> mtimesInner matrix dimensions must agree.
Note the difference between this error and the previous one. This error often occurs because of indexing issues OR
because you meant to use componentwise multiplication but forgot the dot.
Attempting to take the inverse of a singular matrix will result in a warning and a matrix of Infs. It is wise to calculate
the determinant before attempting to take the inverse or, better, to use a method that does not require you to take the
inverse since its not numerically stable.
Attempting to take a power of a nonsquare matrix results in the error
??? Error using ==> mpower
Matrix must be square.
This is usually because you meant to use componentwise exponentiation and forgot the dot.
Indexing errors
Indexing is a pain in MATLAB, it is probably one of the hardest things to get down, especially since the syntax for
an index is the same as the syntax for a function. One annoying fact is that the names of variables are case sensitive,
but the names of functions are NOT. So if you make an array called Abs and you try to index abs(1), it will return 1
no matter what the first value in the array Abs is. Unfortunately, MATLAB will not return an error for this (although
MATLAB v2008+ or so will return a warning saying that this will be changed in a later version), so a good rule of
thumb is never ever name your variables the same as a function. This clears up some indexing problems.
Some things are rather obvious but take some practice in avoiding:
7/31/2019 MatLab Guide Wikibooks
43/86
Error Messages 40
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.
Let's start with a classic mistake:
>> a = 2;
>> if a = 3
??? if a = 3
|
Error: The expression to the left of the equals sign is not a valid target for an assignment.
This error occurs because you meant to see if "a" equaled 3, but instead you told MATLAB to assign "a" a value of
3. You cannot do that on the same line that the if/while statement is on. The correct syntax is
7/31/2019 MatLab Guide Wikibooks
44/86
Error Messages 41
>> if a == 3
>> end
This creates no errors (and you can put anything inside the conditional you want).
You cannot have a normal array with two different classes of data inside it. For example,
>> A = @(T) (1+T)A =
@(T) (1+T)
>> A(2) = 3
??? Conversion to function_handle from double is not possible.
For such a purpose you should use cell arrays or struct arrays.
Here's the tricky one. Take a look at the following code:
>> A = [1,2,3;4,5,6;7,8,9];
>> A(2,:) = [3,5];
??? Subscripted assignment dimension mismatch.
>> A(2,:) = [1,4,5,6];
??? Subscripted assignment dimension mismatch.
>> A(1:2, 1:2) = [1,2,3,4];
??? Subscripted assignment dimension mismatch.
What is happening here? In all three cases, take a look at the dimensions of the left and the right hand sides. In the
first example, the left hand side is a 1x3 array but the right side is a 1x2 array. In the second, the left hand side is 1x3
while the right is 1x4. Finally, in the third, the left hand side is 2x2 while the right is 1x4. In all three cases, the
dimensions do not match. They must match if you want to replace a specific portion of an existing variable. It
doesn't matter if they have the same number of data