#!/usr/local/bin/php
Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in /cgihome/cis520/html/dynamic/2016/wiki/pmwiki.php on line 691
Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in /cgihome/cis520/html/dynamic/2016/wiki/pmwiki.php on line 694
Warning: Use of undefined constant MathJaxInlineCallback - assumed 'MathJaxInlineCallback' (this will throw an Error in a future version of PHP) in /cgihome/cis520/html/dynamic/2016/wiki/cookbook/MathJax.php on line 84
Warning: Use of undefined constant MathJaxEquationCallback - assumed 'MathJaxEquationCallback' (this will throw an Error in a future version of PHP) in /cgihome/cis520/html/dynamic/2016/wiki/cookbook/MathJax.php on line 88
Warning: Use of undefined constant MathJaxLatexeqrefCallback - assumed 'MathJaxLatexeqrefCallback' (this will throw an Error in a future version of PHP) in /cgihome/cis520/html/dynamic/2016/wiki/cookbook/MathJax.php on line 94
Matlab TutorialOn this page… (hide) 1. GoalsThere are two goals of this Matlab tutorial:
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.
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 functions. These have a specific header at the top:
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 n-dimensional array. Unlike other programming languages, Matlab is made so that matrix equations can be translated from paper into Matlab code very quickly: Brackets. Matlab uses [ and ] to denote concatenation, like you would in a math paper. E.g. entering the command >>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 Parentheses. Matlab uses for i = 1:numel(x) x(i) = y(i); end and not for i = 0:numel(x)-1 x(i) = y(i); end which would give an error; there is no zeroth element! Operations. Just as Matlab tries to make typing matrices intuitive, it also makes matrix operations easy. If you have to matrices,
will perform matrix multiplication. Matrix operations are the default for many operators that you will use frequently including 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:
In practice, creating plots is very simple. The process goes like this:
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. Start with 2.5 Vectorization and indexingIndexing.Suppose that
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
Logical indexing.If we have a scalar variable, then a binary operator such as
will return all the values of A which are greater than 5. This is known as logical indexing. If you want to find which rows and columns these occur at, use the
Vectorization. If you find that your code has a large number of 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
Watch for common mistakes with not necessarily clear error messages: ??? 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 logical matrices and a binary matrix are different, and only logical matrices (created through a logical operation, like ??? 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/. |