## Matlab Tutorial
## 1. GoalsThere are two goals of this Matlab tutorial: - To get Matlab beginners up to speed with relevant portions of Matlab that will be needed for this course.
- To teach practical “tips and tricks” to help with debugging, testing, etc. of
*machine learning*Matlab programs.
For the first goal, I will start with the very basics: a highlight of the useful parts of the Matlab interface, key features of programming in Matlab that differentiate it from other languages, how Matlab will make beautiful plots for you, how to use the tools that Matlab provides for debugging and profiling your code, and, most importantly, how to use the vast and enormously helpful documentation library that Matlab ships with. For the second goal, we’ll go through a detailed example of a typical machine learning programming assignment. Debugging a machine learning program can sometimes be tricky; the goal of the program is to “learn” a model of some sort, and in many cases, there is no immediately obvious “correct” output to compare against. ## 2. Concepts - Using the Matlab DesktopHere are some simple lecture notes that I typed up for the initial part of the tutorial, where I describe how to use the Matlab Desktop. Since this is focused on concepts, it’s easier to explain in Wiki format than in comments in an M-file (like the remainder of the tutorial). ## 2.1 The GUIFirst, the basics. The Matlab Desktop works a lot like a typical IDE, such as Visual Studio or Eclipse: the display is broken down into resizable frames into which you can drag and drop various window components. Most likely the default configuration you will see upon starting Matlab for the first time is a three-frame view, with four windows loaded by default into the three frames. We’ll talk briefly about how to use each of these windows. **Command Window**- The Command Window is where the magic happens. Essentially, the Command Window is a very powerful interactive shell. The Matlab shell prompt is the simple double right angle brackets,
`>>` . Just like any other shell, you can navigate the file structure, run scripts and programs, create and destroy variables, and so forth. In addition, the Command Window searches a`path` variable to determine the location of any command that you enter (more on this later). A lot of standard UNIX commands are built-in to Matlab, like`cd` ,`pwd` ,`ls` , etc., as well as windows style commands like`dir` , so it should feel fairly familiar. On UNIX systems, you can access a`sh` shell by prefixing any command with`!` (or with the`system` command), so that you can do pretty much everything that you will ever need to do right from inside of the Matlab Command Window. Finally, the Matlab shell is required to run Matlab scripts and programs (saved in files with a`.m` extension), and accessing the vast scientific computing libraries and capabilities that Matlab provides. **Command History**- The Command History shows a history of the commands you’ve entered into the Command Window. Right click on an entry, and many useful little shortcuts will appear, e.g., creating new scripts from old commands or evaluating them.
**Current Directory**- A standard file browser, and for changing the current directory of the Command Window prompt without needing to run shell commands. Again try right clicking to bring up useful shortcuts.
**Workspace**- This may not be in focus by default (you may need to click on it to bring it up). The Workspace window is a list of all the variables that you have created so far in your Matlab session, usually ignored by most people.
**Editor**- An excellent code and text editor, which you can access by entering
`edit` in the Command Window. If you’re used to Emacs, never fear — in Preferences, you can set the Editor to emulate Emacs keybindings.**The Editor is also Matlab’s debugger, and very useful in that regard.** **Help**-
**THE MOST IMPORTANT WINDOW OF ALL!!!**The help window is not open by default, and many Matlab first-timers take a long time to find it (e.g., me) because the`help` command does**NOT**open up the Help window. Rather, the`doc` command does. The`help` command prints out whatever comments are at the top of a given function or script file, which presumably offer some pointers on how the command is intended to be use. For instance, try`help save` . To access the full documentation for a given command, use`doc save` (or whatever command you are interested in).`doc` will also provide you with a table of contents, and direct you to the innumerable tutorials, demos, and videos that Matlab provides to help you get started on your computational quest.
## 2.2 Concept: The WorkspaceIn addition to being the name of a window, the Workspace is Matlab’s general term for anything that is currently loaded into Matlab’s memory. When you create a new variable, it goes in the workspace; when you load data from saved files, they are loaded into the workspace. You can save your current entire workspace with the >>save myworkspace.mat This tells Matlab to save the current workspace into the Matlab compressed data format file Similarly, you can load variables saved in mat files using the
You can clear variables from the workspace using the ## Workspace scope, and scripts vs. functionsIn matlab, there are two ways to build up libraries of commands that you can use in the future. First, you can simply load up the editor and start typing away. If you save your work to an The other, more powerful way of using code is to create
which tells Matlab that this
which would overwrite the current value of variable ## 2.3 Concept: Basic variable typesMatlab has a lot different variables, classes, etc., but for the most part you never ever seen more than 2 or 3. The most important ones are numeric arrays, strings, cell arrays, structs, and graphics handles. ## Numeric arraysA numeric array is a scalar, vector, matrix, or in general an
>>A = [1 2 3 4] is equivalent to writing
{$A = \left[\begin{array}{cc}1 & 2\\ 3 & 4 \end{array}\right]$} in terms of a natural equation. Equivalently we could have written
for i = 1:numel(x) x(i) = y(i); end and for i = 0:numel(x)-1 x(i) = y(i); end which would give an error; there is no zeroth element!
will perform ## Other variable typesIn Matlab, strings are denoted with single quotes, e.g. mycell = {'cell arrays', 'rock'} Finally, other useful variable types are the ## 2.4 Figures and plottingOnce you start using Matlab, you will never make graphs in Excel ever again. Here’s a basic overview of how Matlab makes beautiful graphics for you. Why do I need to know this, you ask?? Part of the programming assignments will be turning in plots of your results, and because plotting is an extremely useful tool for interacting with and getting to know a dataset. Before doing anything else, plot! Now that that’s out of the way, let’s talk about the high level view of how Matlab organizes your graphics: - The idea is that a figure is just a container; all the actual graphics are drawn to an axes object, which contains both a y and an x axis, any labels, tick marks, colorations, legends, etc., generated automatically. To make kickin plots with multiple graphics organized side-by-side, you use
`subplot` to put multiple axes into one figure container. (See`doc subplot` ). - Technically, A
**figure**is a Window (like any other, that can be snapped in and out of frames, etc.) that can hold one or more**axes**objects. Use`figure` to create figures, and`gcf` to get a**graphics handle**variable to the current figure. Running one of Matlab’s plotting commands will create axes for you, which you can get a handle to using`gca` . Handles can be used to experiment with and set properties of graphics: use`get(gca)` to see a list of all the properties of the current axis and`set(gca, ‘Property’, Value)` to set the property named ‘Property’ to the given Value. - Matlab is designed so that you rarely have to use
`gca` and`gcf` and deal with graphics handles, because there are many useful plotting commands that operate on the*current*figure and*current*axes by default (for instance, the`plot` command is used for most generic plotting purposes.) If you put several of these commands in a row, it will appear that Matlab is only running the last one — in reality, each plot command is using the single current axes and ovewriting the output of the previous command.
In practice, creating plots is very simple. The process goes like this: - First, you have some numeric data that you wish to plot, typically in matrix or vector form.
- So, you (optionally) create or focus on a figure that you want the plot to go into, and then call one of Matlab’s many graphics commands to start drawing the figure you envision. By default commands create new axes and overwrite any old ones; to add additional graphics to an existing axes, you use turn on
*hold*with the command`hold on` , run as many graphics commands as you like, and then turn hold off with`hold off` . - Next, you customize the plot using helpful shortcuts like
`xlim` (to set x-axis limits),`ylim` ,`ylabel` ,`xlabel` ,`legend` , and so forth.*Alternatively*, you can use the`get` and`set` commands above to access advanced options, or double clicking on an element of the figure will activate the figure configuration GUI. - Finally, you can get a beautiful vector-based PDF of your figure by using the Export menu from the Figure, or by calling the
`print -dpdf filename.pdf` command when your current figure is highlighted.
OK, that was all pretty vague and probably didn’t make all that much sense. However, check out the remainder of the tutorial in example code below, and you will see that it works very simply and easily. Furthermore, the graphics commands are documented very well. ## 2.5 Vectorization and indexing
Again, note that this is using 1-based indexing. Now, if we want to get the entire 5th row of
We can also access multiple specific elements using a vector of numbers. To get the 5th row’s 2nd, 3rd and 4th elements, we would write
The colon operator can also be used here. By placing numbers on each side of the colon, we get a list of numbers. The command
will therefore return the vector
and so we can access the same elements of
will return all the values of A which are greater than 5. This is known as
m = zeros(size(A,1),1); for i = 1:size(A,1) m(i) = mean(A(i,:)); end but it is both faster and simpler to just do
Many built-in Matlab functions allow you to pass in an entire matrix as input even if the operation you’re trying to do is on individual elements or rows. Try to vectorize your code as much as possible, it will greatly speed it up and make it easier to read. Take a look at the sample KNN code for a good example of vectorization. ## 2.6 DebuggingWe always have to deal with bugs in everything we do. Luckily, Matlab makes it a little easier to debug by incorporating the debugger into the editor directly. When debugging, the first thing you will want to do is set a debugging stop point any time there is an error: >> dbstop if error; Now, instead of simply returning an error, Matlab will open up the To add additional breakpoints, you can simply click next to the line number in the editor. It is typically easiest to add the above command directly to your matlab startup file. That is located either in ## 3. Further reading & Code TutorialsWe have several code based tutorials; please go through them all, it doesn’t take much time and will show you examples of how to do almost everything you need to do. ## 3.1 Step-by-step introductionIf you’ve never used Matlab before, you should first run through the tutorial instructions give here: Attach:matlab_tutorial1.m Load the file in the Editor and make sure Cell Mode is enabled. This will give you a run-down of all the basic Matlab commands that you need to know, reinforcing the basic concepts given above. ## 3.2 Advanced tutorialOnce you’ve read through the first tutorial, download the following: Attach:matlab_tutorial2.zip This will go through an example of data analysis in Matlab, spends a lot of time talking about using structured data and plotting, and also covers vectorization and other important advanced concepts at the end. ## 3.3 Machine learning exampleOnce you’ve completed both previous tutorials, take a look here: Attach:matlab_tutorial3.zip Start by looking at ## 3.4 MatlabomiconHere Attach:matlab_tutorial4.pdf is a detailed worked example with tips, tricks and general advice, which we’ll probably cover in class. It’s best if you’ve already done the previous tutorials. ## 4. Miscellaneous tips- Remember, if a line is not terminated with a
`;` , the Command Window will display the return value of that statement. To avoid scrolling delays, always suppress outputs with`;` .
??? Subscript indices must either be real positive integers or logicals. Translation: Somehow, you are trying to index or subscript into a matrix with another variable that is numeric, but either has a zero or a negative number. Remember that ??? In an assignment A(:) = B, the number of elements in A and B must be the same. Translation: You have a typo or a bug somewhere in your code. This happens when you trying to assign a subset of one variable values from another variable. Suppose you are trying to assign the j’th row of Error: The expression to the left of the equals sign is not a valid target for an assignment. Translation: You used an assignment ??? Error using ==> mtimes Inner matrix dimensions must agree. Translation: Check the dimensions of your variables — most likely one of them is transposed incorrectly. Matrix multiplication is only valid for {$p \times n, n \times q$} matrices. Octave is an open source alternative to matlab; it is similar, but has slightly less strict syntax, and doesn’t come with the high quality GUI. You can find out more information about Octave at : http://www.gnu.org/software/octave/. |

Page last modified on 08 September 2016 at 10:45 AM