IntroductionWelcome| 00:00 |
(music playing)
| | 00:04 |
Hi I'm Patrick Royal, and welcome to Up
| | 00:06 |
and Running with MATLAB.
What we're exploring here are the core
| | 00:09 |
features and ways of thinking, that will
serve you well as you use MATLAB.
| | 00:13 |
MATLAB is a unique and technical
programming language that's incredibly
| | 00:15 |
powerful when used correctly.
In this course, we'll cover the basics of
| | 00:19 |
programming in MATLAB.
We'll learn about syntax, commands, and
| | 00:23 |
programming structure.
More importantly, though, we'll also
| | 00:26 |
explore what it means to be working in
this programming language, and new ways
| | 00:31 |
of thinking about variables and other
data structures.
| | 00:34 |
We'll look at the different types of
MATLAB programs and how to manage code effectively.
| | 00:38 |
We'll also cover other important topics
for statistical analysis.
| | 00:41 |
Including performance considerations,
display, and user interfaces.
| | 00:45 |
By the end of this course, you can expect
to be comfortable working with a wide
| | 00:49 |
variety of different types of data
through the MATLAB interface.
| | 00:53 |
You'll be familiar with the basic
commands that you'll use every day in MATLAB.
| | 00:56 |
As well as the structure for interpreting
and using new commands.
| | 01:00 |
Welcome to Up and Running with MATLAB.
| | 01:03 |
| | Collapse this transcript |
| What you need to know| 00:00 |
Up and running with MATLAB is designed to
be an introductory course and the MATLAB
| | 00:05 |
programming language itself is a high
level program language.
| | 00:08 |
So you don't need decades of experience
working with computer languages to
| | 00:12 |
understand the topics we'll cover here.
What you should have, though, is a basic
| | 00:17 |
understanding of what computer
programming is and the basic concepts
| | 00:21 |
upon which it is based.
We will cover the following computational
| | 00:25 |
topics in this course.
Variable assignment and manipulation.
| | 00:28 |
For and while loops.
Conditional statements.
| | 00:32 |
Pause, break, and other control flow
commands.
| | 00:35 |
And, functions and arguments.
If you need a refresher on any of these
| | 00:39 |
concepts, I recommend you check out the
Foundations of Programming Fundamentals
| | 00:43 |
course on lynda.com.
If you are comfortable with most or all
| | 00:47 |
of the concepts presented therein, then
you should have no trouble following
| | 00:50 |
along with this course.
The other prerequisites for this course,
| | 00:54 |
are not so much requirements for taking
course as motivations.
| | 00:58 |
MATLAB is a technical language
specifically built around matrix manipulation.
| | 01:03 |
Indeed, the very name is short for matrix
laboratory.
| | 01:06 |
The applications of this software are
numerous and varied from analysis of
| | 01:10 |
financial data to image processing.
For the purposes of this course, I'll
| | 01:15 |
avoid putting too much focus on the
applications, but the examples will
| | 01:19 |
involve analyzing financial data for
summary statistics, such as mean, median,
| | 01:24 |
and T-tests.
If you're not quite sure what these terms
| | 01:27 |
mean, one of the best resources is
actually MATLAB itself.
| | 01:32 |
Anytime I go over a command, you can get
details on what the command is and why
| | 01:37 |
it's significant by typing Help, followed
by the command name into the Command window.
| | 01:43 |
Once you get familiar with it, MATLAB is
an incredibly useful piece of statistical software.
| | 01:48 |
So let's jump right in and start coding.
| | 01:50 |
| | Collapse this transcript |
| Using the exercise files| 00:00 |
I've downloaded the exercise files for
this course to my desktop, and they're in
| | 00:04 |
a folder called Exercise Files.
I'm currently on a PC, but the files will
| | 00:09 |
work the same regardeless of your
operating system.
| | 00:12 |
Inside the folder, each chapter has it's
own folder and in those folders you'll
| | 00:17 |
find sample files for the sample scripts
within.
| | 00:20 |
I will point the files out to you as I
use them in videos.
| | 00:22 |
In the folder for chapter three, you'll
find two key files.
| | 00:26 |
These going along with the videos on
creating scripts and creating function.
| | 00:31 |
And give an example of what your scipt or
function should look like if you followed
| | 00:35 |
all of the steps in the video correctly.
The scripts and functions you create in
| | 00:39 |
those videos will be used in other
videos, so if you skip the videos where
| | 00:43 |
the files are created, you can still use
the key files in later videos.
| | 00:47 |
All of these files are relatively simple,
but they will save you from having to
| | 00:51 |
retype all of the code used if you're
following along.
| | 00:54 |
If you don't have access to the Exercise
Files, you can follow the movie from
| | 00:58 |
scratch, although you might need to pause
once in a while to type the code on screen.
| | 01:02 |
| | Collapse this transcript |
|
|
1. General ConceptsInstalling MATLAB| 00:00 |
If you're interested in learning how to
use MATLAB effectively, the first thing
| | 00:04 |
you'll need to do is get MATLAB
installed.
| | 00:06 |
To acquire MATLAB, direct your browser to
www.mathworks.com.
| | 00:11 |
MathWorks produces a variety of different
software products, including MATLAB.
| | 00:17 |
There are a couple of different ways to
acquire and install MATLAB.
| | 00:20 |
If you are a university student, click on
the Academia tab.
| | 00:24 |
Here, you'll be able to purchase the
student version at a discounted price.
| | 00:29 |
This version includes MATLAB, Simulink,
and ten external toolboxes that provide
| | 00:34 |
additional features and function
libraries to MATLAB.
| | 00:37 |
In Chapter 5, I'll cover three of the
most popular of these add-ons.
| | 00:41 |
If you're not a university student, click
on the Products and Services tab instead.
| | 00:46 |
This will bring up a list of all of the
MathWorks products, including MATLAB and
| | 00:51 |
dozens of external toolboxes.
Under this tab, you can purchase each
| | 00:55 |
MATLAB product a la carte.
All of the toolboxes are compatible with
| | 01:00 |
the main MATLAB software and with each
other, so you can pick and choose the
| | 01:03 |
toolboxes that will be most relevant to
your needs.
| | 01:06 |
Three of the most commonly used toolboxes
are the Symbolic Math Toolbox, the
| | 01:11 |
Statistics Toolbox, and the Optimization
Toolbox.
| | 01:14 |
All of which will be covered in Chapter
5.
| | 01:17 |
When you've chosen which product to
purchase, click on the name to get more details.
| | 01:21 |
On the right-hand side, you can then
choose to either request a trial of the
| | 01:26 |
software or see pricing and licensing
options.
| | 01:30 |
If you request a trial, be aware that
MATLAB will get back to you within about
| | 01:34 |
three days with information about the
license.
| | 01:36 |
It's not an immediate download.
There are separate licenses for
| | 01:40 |
commercial use, academic use, and student
use, as well as for group or individual use.
| | 01:46 |
So be sure to select the license that is
right for you.
| | 01:48 |
Once you've made your choice, click on
View Pricing Now.
| | 01:52 |
And then log in or create an account to
purchase the software.
| | 01:55 |
Once bought MATLAB will automatically
download and install and you'll be given
| | 02:01 |
one or more license keys that can be used
to unlock the software.
| | 02:04 |
With that now out of the way, you're
ready to start coding.
| | 02:07 |
| | Collapse this transcript |
| Understanding the MATLAB interface| 00:00 |
Let's take a look into the MATLAB
interface, when you first open MATLAB,
| | 00:04 |
you will see that the interface is
divided into four windows.
| | 00:07 |
On the left, the current folder window is
placed all the files relevant to MATLAB
| | 00:11 |
in the folder that you are in.
This is where all of the functions and
| | 00:15 |
scripts you create will be stored.
It is important to make sure you are in
| | 00:18 |
the correct folder, when you're running
scripts and functions as MATLAB will
| | 00:22 |
consider the act of folder for the
purpose of running functions.
| | 00:25 |
By default, MATLAB will set the active
folder to a folder called MATLAB in your
| | 00:29 |
Documents folder.
To change the active folder, use the file
| | 00:32 |
path, listed in the top address bar, and
navigate just as you would on a normal
| | 00:37 |
file system.
You can also click on the Browse button
| | 00:40 |
and select a new folder through the
standard files system view.
| | 00:44 |
In the middle of the screen is the
command window.
| | 00:46 |
This area holds all of your input and
output as you run various functions.
| | 00:51 |
As the example I'll type help and press
Enter.
| | 00:53 |
This brings up a list of all relevant
help topics that will appear in the
| | 00:58 |
command window.
Whenever you run a script or a function
| | 01:01 |
any output will be displayed here.
Technically the command window has all of
| | 01:05 |
the same functions as the Script Editor.
So, it is possible to write programs
| | 01:10 |
directly on this line, in practice,
though, you'll probably want something
| | 01:13 |
that you can save, edit, and run multiple
times.
| | 01:16 |
At any time, if the command window gets
too cluttered for your liking, you can
| | 01:20 |
clear it by typing clc and pressing
Enter, or by clicking on the dropdown
| | 01:25 |
arrow in the top right corner of the tile
and choosing Clear Command Window.
| | 01:31 |
On the top right of the screen is the
workspace tile.
| | 01:33 |
This contain the list of all active
variables in your simulation.
| | 01:37 |
To change the information available about
your variables, right-click by the
| | 01:41 |
columns and select which piece of
information you want to display.
| | 01:45 |
You can test out the workspace by
creating a variable now.
| | 01:48 |
Back in the command window type X equals
3 and press Enter.
| | 01:52 |
Notice how the work space now displays
the variable X with a value of 3 and
| | 01:56 |
indicates it is a 1 by 1 matrix, which is
just a scalar.
| | 02:00 |
The work space displays all variables you
used in a given MATLAB session regardless
| | 02:05 |
of which script or function they come
from.
| | 02:07 |
So, after a while it can get cluttered
with old data.
| | 02:09 |
To clean up the workspace, click on the
drop down arrow in the top right of the
| | 02:13 |
tile and choose Clear Workspace.
After you confirm, MATLAB will delete all
| | 02:18 |
existing variables.
Finally, the bottom right of the screen
| | 02:22 |
displays the command history.
This keeps a record of all commands you
| | 02:25 |
type along with the dates and times of
each session.
| | 02:28 |
This feature allows you to easily go back
and see which commands you sent in the past.
| | 02:33 |
You can also copy and paste task commands
to run them again without having to type
| | 02:37 |
them out.
As with the work space, you can clear the
| | 02:40 |
command history by clicking on the drop
down menu and choosing Clear Command History.
| | 02:45 |
Now, let's move on to the top bar where
you'll be creating all of your content.
| | 02:49 |
Starting from the left, the first option
on the home tab is to create a new script.
| | 02:54 |
This is a default option because choosing
a new script simply gives you a blank
| | 02:58 |
canvas to work with.
All of the other options for creating a
| | 03:01 |
new item, just take the script interface
and add some preset formatting.
| | 03:05 |
Clicking on the new drop down menu brings
up a list of all the other types of files
| | 03:10 |
that you can create.
I'll cover these in more detail in future videos.
| | 03:13 |
The last important button is Open.
This will allow you to select a file that
| | 03:18 |
is not in your current folder.
We will cover the variable and code
| | 03:21 |
options here in future videos.
The environment tab can be used to change
| | 03:25 |
the relative position of the tiles in
MATLAB and the default active folder.
| | 03:30 |
The resources tab can be used to access
the online documentation for MATLAB.
| | 03:34 |
If you're ever confused about what a
command does or how it can be used, the
| | 03:38 |
Resources tab is a good place to look for
assistance.
| | 03:41 |
That should be enough to get us started,
next, let's take a look at the MATLAB
| | 03:45 |
language itself.
| | 03:46 |
| | Collapse this transcript |
| Working with MATLAB variables| 00:00 |
Let's take a look at how to create and
manipulate basic MATLAB varialbes.
| | 00:04 |
To start with, we're going to need some
variables.
| | 00:06 |
For now, I'll use the simplest method of
creating variables, typing in command window.
| | 00:11 |
Defining a new variable in MATLAB is very
easy.
| | 00:14 |
Unlike in other programming languages
like C or Java, there's no need to add a
| | 00:19 |
variable declaration statement.
In other words, you don't need to tell
| | 00:23 |
MATLAB something like, this variable is
an integer, or this variable is a string.
| | 00:27 |
Instead, all you need to do is tell
MATLAB what your variable is equal to, so
| | 00:31 |
let's do that now.
In the command window, type A equals 1
| | 00:35 |
and press Enter.
This causes three things to happen.
| | 00:39 |
First, the command window gives you back
the result that A equals 1.
| | 00:43 |
Obviously, that isn't particularly useful
now but if the variable had been defined
| | 00:47 |
as some complicated function, it would
help to know it's exact value.
| | 00:51 |
Second, the command history updates to
include the latest command.
| | 00:55 |
Third, the workspace now shows a new
variable called A with a value of 1 and a
| | 01:00 |
size of 1 by 1.
The sides basically just says that A is a scalar.
| | 01:05 |
For this video, I removed the class
column in the workspace, so right now,
| | 01:09 |
I'm not really sure what type of variable
A is.
| | 01:12 |
It looks like an integer, but it could
just as easily be a double or long.
| | 01:15 |
If I right-click on any of the columns in
the workspace, and choose to show any
| | 01:19 |
variable class, you can see that A is a
double.
| | 01:22 |
But if you were working in a script or a
function, you would have no way of
| | 01:26 |
knowing this.
By default, MATLAB considers any variable
| | 01:29 |
to be a double, and makes calculations
accordingly.
| | 01:32 |
But what if I'd wanted to create a
variable that had a different class?
| | 01:35 |
To manually input the class of the
variable, include the class as a function
| | 01:39 |
in the variable definition.
For instance if I wanted to create a new
| | 01:43 |
variable also equal to 1 that was also an
unsigned integer, I could type in B
| | 01:47 |
equals uint 16 parenthesis 1.
Where unit 16 is a name of the unsigned
| | 01:50 |
16 bit integer class.
For full list of class names you can type
| | 01:56 |
in help class and press Enter.
The results of the command was to create
| | 02:05 |
variable B with a same value and size as
A, but with a class of unit 16 rather
| | 02:11 |
than double.
Changing the class of a variable after
| | 02:14 |
creating it is just as easy.
Simply type in the variable name equals
| | 02:18 |
the new class name, parentheses, with the
variable name again.
| | 02:21 |
For instance, to change A to a character,
you can type in A equals char parentheses A.
| | 02:28 |
Keep in mind that class transformations
may cause some information to be lost.
| | 02:34 |
If you change a double to an integer, for
example, everything after the decimal
| | 02:38 |
point will be truncated away.
So, far I've just looked at scalars, but
| | 02:42 |
MATLAB also supports variables that are
vectors or matrices.
| | 02:46 |
To create a vector in your variable
declaration statement put brackets around
| | 02:50 |
your term, and separate each value within
the brackets with a comma or a space.
| | 02:55 |
For instance, C equals bracket 1 space 2
space 3 causes C to be created as a one
| | 03:03 |
by three vector with those three values
stored in it.
| | 03:06 |
To create a matrix the same principle
applies, except that you use a semi colon
| | 03:11 |
to separate the rows.
For instance D equals bracket 1 common 2
| | 03:16 |
semi colon 3 comma 4 causes D to be
created as a 2 by 2 matrix with those values.
| | 03:23 |
MATLAB always stores the data going
across the rows and then down the columns
| | 03:27 |
as you can see from the output of the
function.
| | 03:30 |
That's the basic of variable definitions.
Every variable has a value a size and a class.
| | 03:35 |
To set or change the class use the name
of the class as a function.
| | 03:39 |
To set or change the size or value, set
the variable equal to whatever data set
| | 03:43 |
you want.
| | 03:43 |
| | Collapse this transcript |
| Everything is a matrix| 00:00 |
Let's examine what it means to say that
everything in MATLAB is a matrix.
| | 00:04 |
One of the key differences between MATLAB
and other programming languages like Java
| | 00:09 |
or C is that MATLAB is built from the
ground up around working with matrices an
| | 00:14 |
large data sets.
This focus can be confusing and
| | 00:17 |
counterintuitive, but it also makes
MATLAB one of the most efficient programs
| | 00:21 |
to do statistical analysis with once you
figure it out.
| | 00:24 |
To start with, I'll open up a new script
by clicking the New Script button.
| | 00:30 |
This opens a popup window where we can
write all of our code.
| | 00:34 |
I'm going to start by writing three
different types of variable definitions.
| | 00:37 |
First, a equals 3.
This means that a is interpreted as a
| | 00:42 |
scalar with a value of 3.
Next, output b equals 3,4,5;1,2,3.
| | 00:50 |
This tells MATLAB that b is a matrix.
Commas or spaces separate different
| | 00:56 |
values on the same row and semicolons or
new lines separate different rows.
| | 01:00 |
Finally, c equals 1:3 causes c to be
interpreted as a vector.
| | 01:07 |
MATLAB automatically expands 1:3 to be
1,2,3.
| | 01:13 |
If I save and then run this file, you can
see that this is exactly what happens.
| | 01:18 |
Now this might seem confusing at first,
because there's no way to know whether a
| | 01:23 |
given variable was a scalar, a matrix, or
a vector.
| | 01:27 |
But in reality, it doesn't matter.
As far as MATLAB is concerned, a scalar
| | 01:31 |
is just one by one matrix and a vector is
just 1 by n or n by 1.
| | 01:36 |
This makes things very simple because the
exact same types of operations can be
| | 01:41 |
used on each of the different variables.
To see how this works, align two new lines.
| | 01:47 |
First, a times b, since a is a 1 by 1
matrix, it is interpreted as a scalar and
| | 01:53 |
multiplied by every value in the matrix
b.
| | 01:56 |
Next, I will put in c times b transpose.
Now, you can't multiply a vector by a
| | 02:02 |
matrix, so MATLAB automatically treats c
like it's a 1 by 3 matrix instead.
| | 02:07 |
The apostrophe after b tells MATLAB to
transpose matrix b.
| | 02:11 |
I have to do this in order to make the
inner dimensions of b and c match.
| | 02:16 |
Now, since we're dealing with matrices,
MATLAB treats the asterisk as matrix
| | 02:21 |
multiplication, rather than scalar
multiplication.
| | 02:24 |
Anytime there is no ambiguity about what
kind of operation you want.
| | 02:28 |
MATLAB interprets your functions in the
most appropriate way, which saves a lot
| | 02:32 |
of time that you might spend defining and
choosing a bunch of different functions
| | 02:36 |
to handle matrix multiplication, scalar
multiplication, dot products, and so on.
| | 02:40 |
| | Collapse this transcript |
| Understanding data structures| 00:00 |
Let's explore the different ways of
representing data in MATLAB.
| | 00:04 |
So far, I've covered creating basic one
and two dimensional arrays in MATLAB, but
| | 00:09 |
MATLAB supports much more complicated
structures.
| | 00:12 |
Creating an array with more than two
dimensions can't be done directly because
| | 00:16 |
there's no simple way to represent three
or more dimensions of data on a two
| | 00:20 |
dimensional screen.
Instead, you can allocate memory for the
| | 00:24 |
array and then define it slice by slice.
To allocate memory for the array, I need
| | 00:28 |
to tell MATLAB what dimensions to use and
what values to put into it.
| | 00:33 |
I'll do this by calling the zeroes, ones,
rand, or randn functions with parameters
| | 00:38 |
representing the dimensions of the array.
For instance, if I type in zeros 2,2,2,
| | 00:45 |
it tells MATLAB to create a 2 by 2 by 2
cubic array where all of the values are 0.
| | 00:52 |
1s creates an array with all the values
of 1, rand creates an array where all
| | 00:57 |
values are random numbers between 0 and
1, and randn creates an array where all
| | 01:03 |
values are normally distributed random
numbers.
| | 01:05 |
Notice that when I define the array,
MatLab automatically displays it in
| | 01:09 |
slices as well.
The first two dimensions of the array are
| | 01:12 |
marked with colons to indicate that they
are fully displayed.
| | 01:15 |
And then MatLab displays the slices
corresponding to each value in the third dimensions.
| | 01:20 |
This extends to arbitrarily large
dimensions and matrices, although it
| | 01:24 |
quickly becomes unwieldy to view the
entire matrix on your command window.
| | 01:29 |
Now, when you are ready to define the
array, you can use exactly the same
| | 01:32 |
syntax to refer to each slice.
For instance, typing in a of colon,
| | 01:37 |
comma, colon, comma 1 equals bracket, 1,
comma 2, semicolon 3, comma 4, causes the
| | 01:45 |
array corresponding to the first z value
of a to take on the indicated values
| | 01:50 |
exactly as if it were a two dimensional
array.
| | 01:53 |
The second way you can define more
complicated matrices is recursively.
| | 01:57 |
MATLAB places no restrictions on what a
matrix cell contains so you can define
| | 02:01 |
the cell of a matrix to itself be another
matrix, to see how this works let's
| | 02:07 |
quickly define four arbitrary matrices,
so a equals 1,2 semicolon 3, 4 b equals
| | 02:16 |
4,3 semicolon 2,1.
C equals 2,2 and D equals 3;3;3.
| | 02:25 |
Now to create a super matrix that holds
each of these matrices as entries, I can
| | 02:29 |
define e equals {a,b;c,d}.
Be sure to use curly braces here rather
| | 02:38 |
than brackets.
Now we see that e is a matrix composed of
| | 02:41 |
four submatrices.
We can then access each of these
| | 02:45 |
submatrices with curly braces again.
So e {1,1,} returns matrix A, and so on.
| | 02:53 |
The last and most general way of holding
data is in a data structure.
| | 02:57 |
Structures are built in MatLab storage
mechanism that allows youto associate
| | 03:01 |
multiple peices of data together.
For instance, you might have a list of
| | 03:05 |
names and addresses, and you might want
to match each name to it's address.
| | 03:09 |
To create a structure and add data to it,
simply define each data field using a dot.
| | 03:14 |
In our example, we would say something
like s dot name equals single quote John Doe.
| | 03:21 |
And then s dot address equals single
quote 123 Fake Street.
| | 03:28 |
To add additional data you can then add
data for S of 2, S of 3, etc.
| | 03:33 |
For instance we could say s of 2.name
equals single quote Jane Roe and s of
| | 03:42 |
2.address equals single quote 124 Fake
street.
| | 03:47 |
As usual, this is considered a matrix, so
your structure can have any number of
| | 03:54 |
dimensions and can even contain
substructures.
| | 03:57 |
Accessing the data works in the same way.
Typing in s of 1,1.name will return just
| | 04:04 |
the name of the first data point, while s
of 1,1 with no qualifier will return the
| | 04:10 |
entire entry.
Inputting s.name with no row or column
| | 04:14 |
number will yield all of the names for
all fields.
| | 04:18 |
With these structures it is possible to
store any type of data no matter how elaborate.
| | 04:23 |
Once created, these structures work in a
similar manner to a map in Java or C but
| | 04:28 |
they have the advantage of allowing any
number of fields for each data point.
| | 04:31 |
| | Collapse this transcript |
|
|
2. Core MATLAB SyntaxBasic commands| 00:00 |
Let's go over some of the basic commands
and syntax that you'll need to write
| | 00:04 |
scripts in MATLAB.
MATLAB is a high level programming
| | 00:07 |
language, so most of the syntax is
relatively simple.
| | 00:10 |
Let's start by opening up a new script by
clicking the New Script button.
| | 00:16 |
Creating and defining scalar variables in
MATLAB is very easy.
| | 00:19 |
All you have to do is type variable name
equals the value and the variable will be created.
| | 00:24 |
The variable can then be referenced by
typing in that same variable name.
| | 00:28 |
If you want to define a variable that
contains multiple scalars, a vector or a
| | 00:32 |
matrix, put brackets around the
definition, and then separate indivudualy
| | 00:36 |
values with commas and spaces, and rows
with new lines or semicolons.
| | 00:41 |
For instance, a equals 4, 0, 2; 1, 2,
3, defines a as a two by three matrix
| | 00:51 |
with 4, 0, and 2 on the top row, and 1,
2, and 3 on the bottom row.
| | 00:55 |
You can see this if we run the script,
and then switch back into the command window.
| | 01:01 |
Now, if we go back into the Script
Editing window, and we change this to a
| | 01:05 |
equals 4 0 2, new line, 1 2 3, and then
run the script again.
| | 01:14 |
Our Command Window will display the same
result.
| | 01:16 |
To define variables as text rather than a
numerical value, put single quotes around
| | 01:21 |
the text you're defining.
If you want your string to be variable
| | 01:24 |
rather than fixed, the functions num2str
and strcat will be useful.
| | 01:30 |
Nam2str converts a numerical value to a
string, allowing for a non-pre-determined
| | 01:36 |
number to be added to the string.
Strcat concatenates two strings
| | 01:40 |
horizontally to form one longer string.
For instance if we switch back to our
| | 01:44 |
script, and defined b equals single quote
hello and C equals single quote world.
| | 01:55 |
We can then say that d equals strcat of b
comma c, and then when we run this and
| | 02:03 |
switch back to the command window, we'll
see that b equals hello, c equals world
| | 02:08 |
and d combines the two of them.
There are two other non intuitive
| | 02:11 |
characters that will be useful in writing
scripts in MATLAB.
| | 02:14 |
To transpose a matrix, put an apostrophe
next to it.
| | 02:17 |
This is an inline function, so you can
transpose multiple matrices within a
| | 02:21 |
single function without needing to define
new matrices on separate lines.
| | 02:25 |
So if we go back to our script, and we
type in a transpose, and then run it.
| | 02:31 |
The command line will now display a with
columns instead of rows.
| | 02:35 |
The second special character is a
semicolon.
| | 02:37 |
Unlike Java, MATLAB does not require you
to place a semicolon at the end of every line.
| | 02:42 |
If you do though, then MATLAB will
interpret it as a command to suppress
| | 02:46 |
output for whatever is happening on the
previous line.
| | 02:49 |
This is an extremely useful function,
because by default, MATLAB displays
| | 02:54 |
results of every single function,
equation, variable definition or loop as
| | 02:59 |
the program runs.
For larger scripts, this can quickly
| | 03:02 |
overwhelm the command window and make the
program unusable.
| | 03:05 |
In general, unless you specifically want
to see the output from a line, it's good
| | 03:10 |
practice to end every line with a
semicolon.
| | 03:12 |
So, if you go back to the script editor,
and we put semicolons at the end of every
| | 03:16 |
line, and then run the function again.
We can see in our command window that
| | 03:23 |
this function has run as normal, all of
the variables are exactly the same as
| | 03:26 |
they were before, but it hasn't added all
of that extra output to the command window.
| | 03:31 |
| | Collapse this transcript |
| Using built-in functions and variables| 00:00 |
In this video, let's take a look at
functions in MATLAB.
| | 00:03 |
Basically, a function differs from a
script in that it has a fixed input and
| | 00:08 |
output channels.
This makes functions extremely useful for
| | 00:11 |
when you're writing complicated programs
that might repeat the same calculations
| | 00:15 |
over and over again.
Rather than rewriting your code, you can
| | 00:18 |
simply pull out that part of it into a
separate function.
| | 00:21 |
MATLAB ships with a wide variety of
functions already implemented.
| | 00:25 |
So we'll start by going over how to use
those.
| | 00:28 |
Perhaps the most commonly used functions
are matrix generation functions which are
| | 00:32 |
used to create a matrix with certain
starter data.
| | 00:35 |
As an example, let's type in a equals
ones 2,3 in the command Window.
| | 00:43 |
This tells MATLAB to generate a new
matrix with two rows and three columns
| | 00:48 |
and then set all of the values in that
matrix to ones.
| | 00:51 |
The zeros function does the same thing
with zeros, the rand function does the
| | 00:55 |
same thing with random numbers and so on.
The important thing to note here is that
| | 00:59 |
all of these functions use the same
syntax.
| | 01:02 |
Type in the function name followed by
parenthesis containing each of the inputs
| | 01:06 |
of the function seperated by commas.
Defining every function in MATLAB is
| | 01:10 |
beyond the scale of this video but there
are several resources that can be used to
| | 01:15 |
find and use new functions.
If you know what you want to do but you
| | 01:19 |
don't know what function to use, then you
can go to the official MATLAB
| | 01:22 |
documentation site,
mathworks.com/help/matlab, and search the
| | 01:26 |
documentation for your queries.
For instance, if I wanted to learn how to
| | 01:30 |
invert a matrix, I could search matrix
inverse and the first result would tell
| | 01:37 |
me to use the inv function.
If you know the name of a function in
| | 01:41 |
MATLAB but you are not sure about the
order or the nature of the inputs, the
| | 01:45 |
best way to find out is to type Help
followed by the function name in the
| | 01:48 |
command Window.
This will return the description of all
| | 01:51 |
the different ways the function could be
used as well as links to similar functions.
| | 01:55 |
For instance, typing help, zeroes, tells
us all the different sets of input that
| | 02:01 |
we could give the function, and what
results each one will return.
| | 02:04 |
It also tells us that we might want to
check out the I and ones functions, which
| | 02:09 |
are also used to generate simple
matrices.
| | 02:11 |
| | Collapse this transcript |
| Working with matrix and scalar operations| 00:00 |
Let's look at the basic matrix operations
in use by MATLAB.
| | 00:04 |
Since MATLAB treats every variable as if
it were a matrix, it's important to
| | 00:09 |
distinguish between operations like
matrix multiplication versus scaler multiplication.
| | 00:14 |
To practice different types of matrix
operations, I'll start by running the
| | 00:19 |
matrix_generator.m script in Exercise
files.
| | 00:23 |
This script simply creates a few sample
matrices that we can then manipulate as
| | 00:28 |
we go through this video.
To start with, type in a plus b in the
| | 00:34 |
command window.
Since matrix a and matrix b have the same
| | 00:38 |
dimension, MATLAB will interpret this as
piecewise addition and will simply add
| | 00:43 |
the corresponding values in each cell of
the matrices.
| | 00:47 |
On the other hand, if you type in a plus
2, MATLAB will interpret this as scalar
| | 00:53 |
addition, so it will add two to every
cell in A.
| | 00:57 |
The same principle works for multiplying
matrices.
| | 01:00 |
If we type in c times d, MATLAB sees that
both of these variables are matrices, and
| | 01:06 |
their inner dimensions match.
So it will automatically carry out matrix
| | 01:10 |
multiplication, on the other hand if you
type in c times 2 MATLAB understands 2 as
| | 01:17 |
a constant and will multiply every term
in c by 2.
| | 01:22 |
Matrix multiplication is a fairly
straight forward process.
| | 01:25 |
But what if we wanted MATLAB to do a
piece wise multiplication of
| | 01:28 |
corresponding entries of the matrix
instead.
| | 01:31 |
Matrices a and b have the same dimensions
but if you just input a times b, MATLAB
| | 01:37 |
doesn't know we want to multiply
corresponding entries.
| | 01:43 |
So it assumes we are indicating matrix
multiplication and throws an error
| | 01:47 |
because the inner dimensions of these two
matrices don't match.
| | 01:51 |
Instead we can add a dot in front of the
asterisk.
| | 01:54 |
Adding a dot in front of any operation,
addition, subtraction, multiplication,
| | 02:00 |
division, exponents, or even equality,
tells MATLAB to execute the operation piecewise.
| | 02:08 |
This is a really efficent way to
manipulate large amounts of data at once
| | 02:12 |
without four loops or recursion.
Now when I run the command it will
| | 02:18 |
generate for me a new two by three matrix
where each entry is a product of
| | 02:23 |
cooresponding entries of matrices a and
b.
| | 02:26 |
Putting a dot in front of an operation
should not be confused with taking a dot
| | 02:31 |
product dot.
if you use vectors E and F, and type in e
| | 02:35 |
dot times f, that will return a new
vector where each entry is a product of
| | 02:42 |
corresponding entries of the matrices..
To do a dot product.
| | 02:46 |
You have to transpose the second matrix.
And then you use simple matrix multiplication.
| | 02:51 |
So, in this example, we would input e
times f, apostrophe.
| | 02:56 |
Where the apostrophe tells MATLAB to
transpose f before it does the calculation.
| | 03:01 |
In general, any time you're working with
1 by 1 matrix, MATLAB will treat them as scalers.
| | 03:08 |
Any time you are working with larger
matrices, MATLAB will treat them as matrices.
| | 03:13 |
If you want MATLAB to perform an
operation piecewise, place a dot in front
| | 03:17 |
of the operation symbol.
If you want to take a dot product, just
| | 03:21 |
treat the vectors like they were
matrices, and then just use matrix multiplication.
| | 03:25 |
| | Collapse this transcript |
| Control flow| 00:00 |
Let's investigate the conveyance used in
MATLAB to set up loops, conditional
| | 00:04 |
statements and other changes to the flow
of the program.
| | 00:07 |
For this lesson open up the
conditionals.m MATLAB file in exercise files.
| | 00:15 |
Conditional statements in MATLAB use the
same IF-ELSE command structure as in many
| | 00:20 |
other programming languages.
In the conditionals.mscript, our goal is
| | 00:25 |
to test whether matrix a is invertible
before we try to invert it, if a is not
| | 00:31 |
invertible, we want to transpose it
instead.
| | 00:35 |
To accomplish this, I'll put an IF
statement before line two.
| | 00:40 |
The only way for this matrix to be
non-invertible is if the 3,3 term in the
| | 00:46 |
matrix is equal to 3.
So in our if statement, we put, if a of
| | 00:53 |
3,3 equals equals 3.
We use double equal signs here because we
| | 00:59 |
are using a comparison rather than
attempting to assign a value to a variable.
| | 01:05 |
Now when I bring the Transpose command
onto this line and press Enter, it will
| | 01:11 |
be indented indicating that it is part of
the if statement, and will only be
| | 01:15 |
executed if the condition is true.
Next, I'll add the line else to tell
| | 01:20 |
MATLAB what to do if the condition is not
true.
| | 01:23 |
The else line should appear before the
inverse statement since that's what we
| | 01:28 |
want to be executed if the condition is
not found true.
| | 01:33 |
The inverse line should appear, after the
ELSE statement, also indented now.
| | 01:37 |
To end the IF statement, simply type end
on the next line and it will
| | 01:42 |
automatically de-indent itself,
indicating that the IF statement is now over.
| | 01:47 |
If we wanted multiple levels of choice, I
could include ELSE-IF statements in the
| | 01:52 |
hierarchy, telling MATLAB to check
additional conditions if the first one
| | 01:56 |
isn't met.
I can also use a switch case statement.
| | 02:00 |
This statement accomplishes the same
thing as the IF statement, but the syntax
| | 02:03 |
is slightly different.
In this instance, I would start by saying
| | 02:09 |
switch of a of 3,3.
This tells MATLAB that all of the
| | 02:15 |
following cases will deal with the value
of the number in a of 3,3.
| | 02:20 |
Now, add a line, saying case three,
followed by the transpose line.
| | 02:26 |
This tells MATLAB that if it is the case
that a of 3,3 equals 3, it should perform
| | 02:31 |
the transpose.
Next, to tell MATLAB what to do if the
| | 02:37 |
case is not met, replace the ELSE keyword
with the OTHERWISE keyword.
| | 02:43 |
The statement block after otherwise will
only execute if none of the cases are met.
| | 02:50 |
Finally, we still need an end statement
as before to tell MATLAB that the block
| | 02:54 |
is done.
This basic syntactical structure applies
| | 02:58 |
for WHILE loops, FOR loops, and TRY-CATCH
statements.
| | 03:02 |
In all cases, the block begins with the
keyword followed by some condition.
| | 03:08 |
All of the statements to be executed are
indented and then the block ends with the
| | 03:12 |
END keyword.
The other two important keywords in
| | 03:15 |
MATLAB are break and continue, both
appear on their own within a for or while
| | 03:21 |
loop And simply tell the program where to
go in relation to that loop.
| | 03:25 |
Break tells MATLAB to jump completely out
of the loop and resume execution at the
| | 03:31 |
end statement.
Continue tells MATLAB to jump to the
| | 03:35 |
beginning of the loop, check the
condition again, and then if it still
| | 03:39 |
holds, execute the loop as normal.
| | 03:41 |
| | Collapse this transcript |
| Understanding data types| 00:00 |
Let's look at the ways in which MATLAB
represents and understands numerical data.
| | 00:05 |
Normally, when programming, it's easy to
ignore data types and just assume that
| | 00:10 |
the program knows what it's doing.
The assumption is that MATLAB will give
| | 00:14 |
the exact answer to any calculation
because it uses so many decimal points
| | 00:19 |
that the error is extremely tiny.
However these tiny errors can cause huge
| | 00:24 |
problems, making it important to have
some grasp over the difference between
| | 00:28 |
different types of ints and doubles.
For an example of this see
| | 00:32 |
roundoff_error.m in the exercise files.
This graphs two exponential decay
| | 00:39 |
sequences on a logarithmic graph.
We'll go into more detail about the exact
| | 00:44 |
mechanics behind graphing and how to use
graphing functions in a later video.
| | 00:49 |
Both sequences change by the exact same
amount each time.
| | 00:53 |
The only difference is the starting
point, so they should be parallel.
| | 00:57 |
We would expect both sequences to go
uniformly downward in a straight line,
| | 01:02 |
but that's only true of sequence x.
Running this sequence yields the graph
| | 01:06 |
where x is going down uniformly as
expected, but sequence y goes down
| | 01:12 |
parallel only for a while and then
suddenly turns upward and diverges.
| | 01:17 |
This occurs because of the specific way
MATLAB rounds off very small numbers, and
| | 01:22 |
as we can see, the end result is more
than a trillion trillion times higher
| | 01:26 |
than it should be.
There are several ways of dealing with
| | 01:29 |
problems like this.
First, we can change the data type.
| | 01:33 |
Depending on the type of problem,
switching from a less precise data type
| | 01:37 |
to a more precise one may reduce or
remove roundoff errors.
| | 01:41 |
On the other hand, switching to a less
precise data type where precision isn't
| | 01:46 |
as important can save space on your hard
drive.
| | 01:49 |
Either way to change the data type use
the name of the new type as a function
| | 01:54 |
with the variable or number inside.
For instance, if I go back to the command
| | 01:59 |
window and type x equals unt64 of 1024
then x will be defined as a 64-bit
| | 02:06 |
unsigned integer with a value of 1024.
Note that data must be of the same type
| | 02:17 |
in order for it to be combined in an
expression.
| | 02:20 |
So it's good practice to pick a single
data type and use it for all values in
| | 02:24 |
your program.
The other way of dealing with roundoff
| | 02:27 |
errors is by using symbolic arithmetic.
This means that MATLAB will consider data
| | 02:33 |
as rational fractions rather than
decimals which completely removes all rounding.
| | 02:38 |
Using symbolic numbers require the
symbolic math toolbox which we will cover
| | 02:43 |
in more detail in chapter five.
The downside of using symbolic math
| | 02:47 |
though, is that symbolic arithmatic is
significantly slower than ordinary
| | 02:52 |
floating point arithmatic.
To use symbolic arithmetic, simply put
| | 02:57 |
sym and parenthesis around each of the
numbers that you'd use to designate it as
| | 03:02 |
a symbolic data type.
Be sure to put this around all of the
| | 03:06 |
numbers in variable assignment statements
because you must have data of the same
| | 03:11 |
type in order for MATLAB to be able to do
a calculation with it.
| | 03:15 |
Looking back at the previous example, if
we go back to roundoff error and add sym
| | 03:21 |
around each of the two variables in
sequence y, then when we wrap it again we
| | 03:30 |
would get the correct result.
As we can see now, both of the lines are
| | 03:34 |
now going down in a uniform and parallel
fashion.
| | 03:37 |
| | Collapse this transcript |
|
|
3. Programming in MATLABHow are program files stored?| 00:00 |
So far, we've assumed that all your
MATLAB files are stored in the same folder.
| | 00:06 |
Obviously though, you'll eventually have
enough separate scripts and programs that
| | 00:10 |
you'll need multiple folders.
So, in this video, we're going to look at
| | 00:14 |
ways to navigate between folders in the
MATLAB interface.
| | 00:18 |
The current folder that MATLAB is working
in is always displayed in the top bar of
| | 00:23 |
your screen in a breadcrumb trail.
From this trail, you can click on any of
| | 00:27 |
the upper folders to jump back to them.
For instance, I can click on my user name
| | 00:32 |
to jump back to that folder.
From here, I can navigate to any of the
| | 00:35 |
files within simply by double-clicking on
the relevant folders.
| | 00:40 |
For example, if I double click on
desktop, and then exercise files, I can
| | 00:45 |
see and work with the MATLAB files
inside.
| | 00:48 |
Navigating between folders is obviously
useful for finding MATLAB files that you
| | 00:53 |
want to edit.
But it is also important for the way that
| | 00:56 |
MATLAB is run.
By default, MATLAB can only find .m files
| | 01:02 |
that are either included in the program
by default.
| | 01:05 |
Or present in your currently active
folder.
| | 01:07 |
This means that if a certain file is
referenced by your script, it must also
| | 01:12 |
be in the active folder or else MATLAB
won't be able to find it.
| | 01:16 |
MATLAB also has a few folders that are
included by default in its search called
| | 01:22 |
the Search path.
These include all folders provided by the
| | 01:25 |
MATLAB installation as well as all
folders within the MATLAB userpath folder
| | 01:31 |
in your documents folder.
If you want MATLAB to look into
| | 01:34 |
additional folders you can add them to
the Search Path by typing addpath
| | 01:40 |
Followed by the file path.
For instance, we can add the exercise
| | 01:44 |
files folder by typing addpath of C slash
users slash your username slash desktop
| | 01:56 |
slash exercise files.
Since you don't always know where or when
| | 02:03 |
a script will run, it's a good practice
to have your script call addpath with the
| | 02:08 |
path of any other function that it's
planning on referencing.
| | 02:11 |
| | Collapse this transcript |
| Viewing and editing programs| 00:00 |
Lets look at the bread and butter of
MATLAB.
| | 00:03 |
Viewing, Editing, and Running programs.
Creating a new program is easy.
| | 00:07 |
Simply click on the New Script button, to
generate the script and automatically
| | 00:12 |
open up the Script Editor window.
Here, you can type in all the code that
| | 00:17 |
will run as a part of the program.
For this example, we'll just create a
| | 00:21 |
very simple script that generates a
random two by three matrix.
| | 00:25 |
So P equals rand 2,3.
When you're ready to save, click on the
| | 00:32 |
Save button and then give the program a
name.
| | 00:37 |
And it will automatically save to the
active folder.
| | 00:40 |
Now, any time you want to get back to the
script to edit it, simply double-click on
| | 00:46 |
the name in the current folder pane and
this will reopen the window and allow
| | 00:50 |
editing of the script exactly as before.
To run the program, there are several
| | 00:55 |
different option.
First you can click on the Run button
| | 00:59 |
within the Editing window.
This runs the program immediatly without
| | 01:03 |
closing the window, allowing you to
quickly and easily see how changes to the
| | 01:07 |
program effect the output.
Second, you can right-click on the script
| | 01:11 |
from within the current folder window.
And choose Run or press F9.
| | 01:17 |
Finally, you can run the script by typing
it's name into the Command Window and
| | 01:22 |
pressing Enter.
This final method is esspecialy useful if
| | 01:28 |
your script is a function, since this is
the only way to provide the inputs.
| | 01:33 |
When running a function, it is important
to make sure you provide the correct
| | 01:37 |
inputs in the command statement.
Each argument must be a variable of the
| | 01:41 |
proper type and dimensions in order to be
acceptable.
| | 01:44 |
Unlike other programming languages,
MATLAB doesn't have a variable definition statement.
| | 01:50 |
So it will not be able to tell you what
format or what dimensions you need for
| | 01:54 |
the variables, just their names.
Instead it will attempt to run the
| | 01:58 |
function with whatever data is provided
which can lead to unpredictable behavior.
| | 02:04 |
Because of this, it's good practice to
make the variable names in your functions
| | 02:08 |
as descriptive as possible.
For instance, rather than naming the
| | 02:11 |
variable p, it would be a good idea to
change the theme to something like stock prices.
| | 02:19 |
It's also never a bad idea to add checks
in the program.
| | 02:22 |
For instance, if your function requires a
3 by 3 matrix, the first line of it might
| | 02:27 |
be to check if the matrix dimensions are
3 by 3.
| | 02:31 |
If not, the function would exit and throw
an error message.
| | 02:34 |
That's the basics of editing and running
programs within MATLAB.
| | 02:38 |
| | Collapse this transcript |
| Creating scripts| 00:00 |
Let's practice writing simple scripts in
MATLAB by creating a program that
| | 00:05 |
provides some summary statistics for a
list of daily prices for the SMP 500 from
| | 00:09 |
2000 to 2010.
The sample data can be found in the
| | 00:12 |
excersize files for chapter three.
To start with, click the New Script
| | 00:19 |
button to open up the script editor
window and save it as practice scripts.m.
| | 00:29 |
Here you can write the relevant commands
an run the script.
| | 00:33 |
The first thing we need to do is to load
the chosen data into the function.
| | 00:37 |
It can't directly reference a file in its
formulas.
| | 00:41 |
I won't go into a lot of detail about
file formats in this video but MATLAB can
| | 00:46 |
automatically convert CSV files into
matrices.
| | 00:50 |
So you can simply use the CSV read
function.
| | 00:54 |
I'll start by defining a new variable
called stocks.
| | 00:58 |
And set it equal to CSV read of sample
data.csv.
| | 01:07 |
The data in this file has only one column
containing the clothes prices so the
| | 01:12 |
matrix should be 2515 by 1.
If you run the script that is exactly
| | 01:18 |
what you will see.
From here manipulating the data is as
| | 01:22 |
simple as calling the appropriate
functions.
| | 01:25 |
An easy one to start out with is finding
the mean.
| | 01:28 |
So we could write mean of stocks.
If you just want the output to go to the
| | 01:33 |
command window you don't need a separate
function.
| | 01:36 |
Instead you can just leave off the
semicolon at the end of the line and the
| | 01:41 |
result will automatically display.
So when we run this in the command window
| | 01:45 |
we can see that we have the mean here.
Scripts can also contain more complicated formulas.
| | 01:51 |
For instance if you wanted to split the
data by year and then display each of
| | 01:55 |
those means, you could use a for loop as
follows.
| | 01:58 |
There are 10 years.
So the first line would be for I equals 0
| | 02:04 |
to 9.
i is simply a dummy variable used to keep
| | 02:08 |
track of the loop counter.
The next line needs to calculate the mean
| | 02:13 |
of just 1 10th of the matrix.
To reference just that part you can say,
| | 02:18 |
stocks of 250 times I plus 1 to 250 times
i plus 250.
| | 02:26 |
This formula might look a bit confusing
but it basically just tells the program
| | 02:31 |
to start at the given year where each
year is 250 business days and then only
| | 02:36 |
consider the next 250 values.
You can then surround this with a mean
| | 02:41 |
function as before to get mean of stocks
of the current day to 250 days in the future.
| | 02:50 |
Again leave off the semi colon to insure
that the output displays.
| | 02:55 |
From here all you have to do is end the
loop and run the script to see the results.
| | 03:02 |
These are the basics of creating a
script.
| | 03:04 |
You can do anything that I've covered in
previous videos in a script and it will
| | 03:09 |
run exactly as if it were on the command
window.
| | 03:12 |
The advantages of a script are twofold.
First, complicated loops, conditional
| | 03:17 |
statements and so on are much simpler to
work with if you have multiple lines and
| | 03:22 |
plenty of space.
Second, whatever you type into a script
| | 03:26 |
so that you can refer back to it and run
it again whenever you need to.
| | 03:30 |
| | Collapse this transcript |
| Creating functions| 00:00 |
Let's investigate how to create a simple
function in MATLAB.
| | 00:04 |
Functions are very similar to scripts in
many ways but they have different output
| | 00:09 |
and input protocols.
Whereas a script is meant to run on its
| | 00:13 |
own and runs the same way every time.
A function takes an input from the user
| | 00:18 |
each time it runs.
Making it a more general and powerful tool.
| | 00:22 |
Similarly whereas scripts don't usually
have predefined output other than what is
| | 00:28 |
displayed on the command window or on a
plot.
| | 00:30 |
Functions directly provide their output
for use by other scripts or functions
| | 00:35 |
that call them.
For this video I will rewrite the script
| | 00:38 |
created in the previous video into a
function.
| | 00:41 |
To start with, click on the New dropdown
menu and choose to create a new function.
| | 00:47 |
Then save that function as
practicefunction.m.
| | 00:54 |
Right away you will see that rather than
providing a blank screen, MATLAB
| | 00:59 |
automatically writes in some basic
information.
| | 01:02 |
The first line is the most important
because it defines how the function can
| | 01:06 |
be used.
Essentially when you type in the function
| | 01:09 |
name followed by input args, the function
will return output args.
| | 01:14 |
Because I changed the name of our
function when I saved it, go ahead and
| | 01:18 |
change the name of the function from
untitled to practice functions.
| | 01:26 |
For this function as before, you can
calculate the mean of the stock prices.
| | 01:31 |
Here however, you don't need to define a
matrix of the data because we can assume
| | 01:35 |
that it will be given to us in input
args.
| | 01:38 |
So I'll simply add the line mean of input
args.
| | 01:44 |
We can do the exact same thing with the
for loop.
| | 01:47 |
So to save time, I'll simply copy and
paste the code from our sample script.
| | 01:53 |
If you're following along on your
computer, you can pause here to retype
| | 01:56 |
the selected code.
Don't forget to change stocks to input
| | 02:05 |
args to make sure we have the proper
variable name.
| | 02:09 |
We do need to make one change though.
If you want the function to have output,
| | 02:14 |
you need to define it.
So rather than just calculating the mean
| | 02:18 |
and the displaying it in the command
window, you can add it to output args.
| | 02:22 |
In this case, simply say that output args
of I plus 1 equals the mean within the
| | 02:31 |
for loop.
Matlab will automatically define output
| | 02:34 |
args as a 10 by 1 matrix to hold the
data.
| | 02:37 |
Once you have that you're done.
So go ahead and save your function and
| | 02:42 |
you will be able to run it.
And MATLAB will automatically handle the
| | 02:45 |
outputting of the output args function.
Now let's run the function.
| | 02:49 |
Go to the command window and type in a
equals practice function of csv read of
| | 02:59 |
the sample data.csv.
If the function was created correctly,
| | 03:05 |
MATLAB will display the mean.
And then define matrix a to hold all of
| | 03:10 |
the output data from the function.
And that is exactly what we see here.
| | 03:14 |
| | Collapse this transcript |
| Debugging| 00:00 |
Even the best coder, is unlikely to write
a script that runs perfectly the first
| | 00:04 |
time, and coding in MATLAB is no
exception.
| | 00:07 |
To help with debugging, MATLAB provides
several different methods of getting a
| | 00:12 |
closer look at the mechanics of your
functions as they run so that the problem
| | 00:16 |
can be identified.
The simplest step to take when a bug is
| | 00:19 |
encountered is to remove the semicolons
from every line in the suspect area.
| | 00:23 |
This causes MATLAB to display the output
from every single calculation,
| | 00:28 |
potentially allowing you to spot the
problem.
| | 00:30 |
In fact, unless you have a long loop with
lots of data that can't be displayed
| | 00:34 |
easily, there's no reason not to leave
off semicolons entirely, at least until
| | 00:39 |
the program is working to your
specifications.
| | 00:41 |
If that doesn't solve the problem, the
next step is to run the program in
| | 00:45 |
sections by specifying breakpoints.
Breakpoints can be added from within the
| | 00:49 |
Editor Window, so we'll open up the
practice script that we worked on in an
| | 00:53 |
earlier video, so we can add them now.
Breakpoints are added in the Breakpoints
| | 00:58 |
drop down menu.
To set a breakpoint on a certain line,
| | 01:01 |
click on the drop down menu and then
click Set/Clear breakpoint.
| | 01:06 |
In this example, I'll set a breakpoint
right after the first line so that the
| | 01:10 |
program will pause before it tries to
calculate the mean of the stock.
| | 01:14 |
Now when the program runs, it will
automatically stop at the indicated line
| | 01:18 |
and reopen the function.
From here, you can see exactly the
| | 01:22 |
current state of the function, so if a
variable is out of place, you could find it.
| | 01:26 |
In this case, because we put a break
point right after reading in the file, it
| | 01:30 |
would be easy to see if there was an
error with the file reading, or if the
| | 01:33 |
file could not be found, or if some other
problem manifested.
| | 01:37 |
When ready, you can click Step to run the
next line of the function, or Continue,
| | 01:41 |
to continue function as normal until the
next break point.
| | 01:46 |
Once the break point is set, it can be
enabled or disabled in the same dropdown
| | 01:51 |
menu, so you can just add break points at
critical sections of your script from the
| | 01:55 |
beginning, and simply enable them
whenever a problem is encountered.
| | 01:59 |
Conditional breakpoints are a little bit
more complicated.
| | 02:02 |
In this case the breakpoint will only
activate if a specific condition is met.
| | 02:06 |
If you know that a variable is taking on
an inappropriate value at some point in
| | 02:10 |
the function but you're not sure when a
conditional breakpoint can help you find
| | 02:14 |
the exact point of the divergence.
These breakpoints are also useful if you
| | 02:18 |
want to break at a specific iteration of
a loop.
| | 02:21 |
Rather than every time the loop executes.
The final settings that can aid in
| | 02:25 |
debugging are the error handling codes.
By default, a program will continue to
| | 02:30 |
execute if it runs into a warning or
completely quit if it returns an error.
| | 02:35 |
Instead, checking the Stop on Error or
Stop on Warning options will cause the
| | 02:39 |
program to treat the error like it's a
break point and just pause.
| | 02:43 |
The advantage of this is that the state
of the program at the time when the error
| | 02:47 |
occurred is saved, so it can be easier to
find the cause.
| | 02:50 |
Between line by line output, breakpoints
and error handling, finding an error in
| | 02:55 |
MATLAB should be as pain free as
possible.
| | 02:57 |
| | Collapse this transcript |
| Performance considerations| 00:00 |
Computers today are extremely fast and
they will undoubtedly get exponentially
| | 00:05 |
faster in the future.
Despite this, computing time is still a
| | 00:09 |
finite resource.
And it saves time and money to design
| | 00:13 |
programs that run as quickly and
efficiently as possible.
| | 00:17 |
In general, computing time is displayed
in big O notation, which is a quick and
| | 00:22 |
dirty representation of the rate at which
the number of calculations scales with
| | 00:27 |
the data set size.
For instance a program with o of n run
| | 00:31 |
time would take twice as long to process
a data set with twice as many values.
| | 00:38 |
While a program with O of n squared,
would take two squared, or four times as
| | 00:42 |
long, to process the same double data
set.
| | 00:45 |
The steepest scaling, is exponential,
such as, O of two to the n.
| | 00:50 |
This means that calculations would take
twice as long for a data set with just
| | 00:55 |
one more value, making the program only
feasible to run for extremely small
| | 00:59 |
amounts of data.
The time of function in MATLAB use the
| | 01:03 |
Tic and Toc functions.
The Tic function starts a built-in stop
| | 01:08 |
watch function that measures computing
time to the millisecond.
| | 01:12 |
While the Toc starts the function and
returns the amount of time elapsed.
| | 01:17 |
The general syntax for these functions,
is to put tic on the line before whatever
| | 01:22 |
part of the function you want to time and
then store the output of talk in a
| | 01:27 |
permanent variable by typing the variable
name equals talk.
| | 01:31 |
The stopwatch can be used multiple times
and assigned to multiple variables.
| | 01:35 |
So it's easy to time each critical part
of the function and record the execution
| | 01:40 |
time of each one.
As an example, we can use the practice
| | 01:44 |
script that you created in a previous
video.
| | 01:47 |
So, I'll open that, and if you wanted to
time this function, on the first line,
| | 01:53 |
we'd put a tic function.
And then on the last line we would put a
| | 01:58 |
toc function.
Then when we run, we could see that it
| | 02:02 |
would now display that the elapsed time
is .024 seconds.
| | 02:06 |
Optimizing functions themselves to reduce
their big O value is an extremely
| | 02:11 |
complicated subject, and beyond the scope
of this course.
| | 02:15 |
But there are several coding practices in
MatLab that can significantly reduce the
| | 02:20 |
time a program takes to run.
First, be sure to put semicolons after
| | 02:25 |
every line that doesn't have output that
is absolutely necessary for the user to see.
| | 02:29 |
Writing output to the command window
slows down the execution of the program
| | 02:34 |
substantially, and simple calculations
can take an inordinate amount of time.
| | 02:39 |
This is especially important in loops or
when dealing with matrices with hundreds
| | 02:43 |
of thousands of values.
The second good practice is to allocate a
| | 02:47 |
variable only once.
It takes far less time for MATLAB to
| | 02:52 |
define a 100 by 100 matrix of 0's, and
then fill it cell by cell than it takes
| | 02:58 |
for MATLAB to define a 1 by 1 matrix then
extend to 1 by 2, then 1 by 3, and so on
| | 03:05 |
all the way up to 100 by 100.
The 0's and 1's functions are useful here
| | 03:10 |
since they allow you to set the
dimensions of a matrix and fill it with
| | 03:13 |
placeholder data.
Going back to the practice script, if we
| | 03:18 |
wanted to store all the stock data in a
single matrix, we would start by defining
| | 03:23 |
the matrix on the line above, stock,
data, equals 0's of 10,1.
| | 03:29 |
And then within the loop you would stay
stock data of I plus 1 comma equals E to means.
| | 03:40 |
This would ensure that matrix is defined
only once, which makes it much faster for
| | 03:44 |
MATLAB to run.
Finally, be sure not to make MATLAB do
| | 03:48 |
any more calculations or hold any more
data than necessary to get the answer.
| | 03:53 |
It's easy to just make every variable a
double or an unsigned integer of 64 bits,
| | 04:00 |
but this wastes a lot of space, and it
forces MATLAB to do calculations on far
| | 04:05 |
more digits than is necessary in most
cases.
| | 04:08 |
Symbolic arithmetic is even worse for
speed.
| | 04:10 |
While it will completely eliminate
rounding errors, it also takes many times
| | 04:14 |
longer to run than normal arithmetic.
Variables can be left as high precision
| | 04:19 |
values while you're writing the script to
avoid any rounding errors while
| | 04:23 |
debugging, but once the program is
complete, it can significantly reduce the
| | 04:27 |
run time to go back and change variable
to single or 8 bit integer wherever
| | 04:33 |
higher degree of precision are
unnecessary.
| | 04:35 |
| | Collapse this transcript |
| Adding program documentation| 00:00 |
In previous videos we've looked at the
tools Matlab provides to write and debug
| | 00:05 |
good programs.
But writing good code is only half the battle.
| | 00:08 |
In the modern world, the vast majority of
programming projects are much to large
| | 00:13 |
for an individual to complete.
So documenting your code in a readable
| | 00:16 |
fashion is of paramount importance.
Let's look at the syntax for adding
| | 00:20 |
comments and help files in Matlab.
In this video we'll use the
| | 00:24 |
practice_script.m file that you created
in the creating scripts video, earlier in
| | 00:29 |
this chapter.
To designate a line, or the latter part
| | 00:33 |
of a line as a comment.
Simply put a percent sign directly before
| | 00:37 |
the comment.
In this example, you might want to
| | 00:39 |
clarify the first line of code, to let
the reader know that it is converting the
| | 00:44 |
CSV file into a MatLab matrix.
So you can simply write percent.
| | 00:49 |
Converts CSV to matrix.
Another common use of commenting is for
| | 00:55 |
debugging purposes.
Commenting out a suspect line is an easy
| | 00:58 |
way to see if it was the command causing
whatever error the program is throwing.
| | 01:03 |
To designate more than one line at a time
as a comment, use block quotes.
| | 01:07 |
At the beginning of the comment block,
type % and {.
| | 01:09 |
So if we wanted to comment out the loop
here, we type %{ in front of the loop.
| | 01:16 |
This doesn't have to be on its own line,
but it's often easier to see and work
| | 01:19 |
with if it is.
Then, at the end, type %} facing the
| | 01:24 |
other way.
Everything between these two bookends
| | 01:27 |
will now be commented.
As before, this is a great way to handle
| | 01:31 |
debugging, as well as provide
documentation.
| | 01:34 |
Comments can also be used within a line.
If you only want to comment out part of a
| | 01:38 |
line of code with normal code on either
side, you first have to split up the line.
| | 01:42 |
This is done by putting an ellipse
directly before the line break, so we'll
| | 01:47 |
uncomment out the block.
And if we wanted to comment out just part
| | 01:51 |
of the stock formula, we could in and put
a ellipses right before this number, and
| | 01:57 |
then press enter.
Now to comment out that part of the line,
| | 02:00 |
you put a second ellipse, before the
numbers.
| | 02:04 |
And then one final ellipses afterwards,
so that you can move it on to the next
| | 02:09 |
line and ensure that this next part is
considered part of the line again.
| | 02:13 |
This ellipses tells Matlab that
everything to the right of it is a
| | 02:17 |
comment and that the command continues on
the next line.
| | 02:20 |
Inline comments like this should
generally be used sparingly for
| | 02:24 |
documentation as they can make your code
more confusing.
| | 02:27 |
They are however quite useful for
narrowing down individual terms in a
| | 02:31 |
function that might be causing a bug.
The other special type of comment is a
| | 02:35 |
help comment.
This is a descriptor that is
| | 02:38 |
automatically applied to a comment at the
very beginning of your script or right
| | 02:42 |
after the function definition in a
function.
| | 02:44 |
This comment is meant to describe the
program as a whole to anyone else that
| | 02:48 |
comes along and uses it.
Unlike the other comments, it can be
| | 02:51 |
viewed without opening up the script or
function itself.
| | 02:55 |
Typing in Help followed by the function
name will return this help comment within
| | 02:59 |
the command window.
For instance, at the beginning of this
| | 03:01 |
function, I could add a new line with
percent practice script calculates the
| | 03:11 |
rolling mean of stock data.
Then if I save this, go to the command
| | 03:18 |
window and type help practice script, it
will return the help message.
| | 03:25 |
Between ordinary comments, inline
comments, and help messages,
| | 03:29 |
understanding code should be much more
straight forward.
| | 03:32 |
| | Collapse this transcript |
|
|
4. Data RepresentationsCreating basic plots| 00:00 |
Let's look at ways of displaying data in
MATLAB.
| | 00:03 |
The basic functions for plotting a two
dimensional graph in MATLAB is the plot fucntion.
| | 00:08 |
There are a wide variety of syntaxes for
this function, allowing you to change
| | 00:11 |
many of the settings of the plot as it's
created.
| | 00:14 |
The simplest plot takes a single vector
of data and plots the data values against
| | 00:18 |
the index number of the data in the
vector.
| | 00:20 |
For example, I can import the
dailydata.csv file in the exercise files,
| | 00:29 |
and then just make sure that all 3
columns are selected and import them into MATLAB.
| | 00:34 |
This displays the date, closing price,
and volume of shares traded for the S&P
| | 00:39 |
500 for each day from the year 2000 to
2009.
| | 00:44 |
The date in this case is displayed as the
number of days since 1900.
| | 00:48 |
This is an often-used format, which makes
it easy to do math on the days rather
| | 00:53 |
than worrying about going from one month
to the next and not having the same
| | 00:57 |
number of days in each month.
Once the data is imported, you can type
| | 01:02 |
the command plot, close and it will
automatically plot the closing price
| | 01:08 |
versus the index of the data set.
Just having an index value isn't very
| | 01:12 |
useful though, so I can improve the graph
by changing it to plot(Date,Close).
| | 01:18 |
Using two datasets tells MATLAB to
consider the first dataset as the
| | 01:23 |
independent variable and the second as
the dependent variable.
| | 01:27 |
In this case, the independent variable is
equally spaced so the graph itself
| | 01:30 |
doesn't change, but it does update the
access to get more useful information.
| | 01:35 |
Once information is plotted, it can be
edited in the figure window by clicking
| | 01:39 |
on the Tools dropdown menu and choosing
Edit Plot or by running the Plot Edit
| | 01:44 |
command in the Command window.
In this mode, double-clicking any element
| | 01:49 |
of the plot will allow you to select and
modify it.
| | 01:52 |
For instance, double-clicking the plotted
line lets me choose the x and y data
| | 01:57 |
sources, the color of the line, and the
shape and color of the markers.
| | 02:00 |
I can even change the plot type entirely,
choosing among lines, bar graphs, area
| | 02:05 |
graphs, stair graphs, or stim plots.
MatLab doesn't just disply 2 dimensional
| | 02:10 |
graphs, of course, it also allows for the
plotting of 3 dimensional graphs.
| | 02:14 |
Here, the relevant command is plot 3.
Going back to the command window, we can
| | 02:18 |
type in plot 3, and then put in all 3
variables that we want to include this time.
| | 02:24 |
The syntax is almost exactly the same.
So we would just put date comma volume
| | 02:29 |
comma close.
And this would allow us to see how the
| | 02:33 |
value of the S&P 500 relates to both the
date and the volume of shares traded for
| | 02:38 |
that day.
Once generated this graph can be viewed
| | 02:41 |
and edited in the same way as a two
dimensional graph.
| | 02:44 |
One tool that might prove specifically
useful for this kind of graph, though, is
| | 02:48 |
the Rotation tool.
Clicking the Rotation icon and then
| | 02:52 |
clicking and dragging on the Plotting
window will change the perspective on the
| | 02:55 |
graph, often making it easier to see and
understand.
| | 02:58 |
| | Collapse this transcript |
| Adding annotations| 00:00 |
A plot is a wonderful thing.
But, unlabeled, it's only useful to the program.
| | 00:04 |
For graphs meant for public view, it's
important to include titles, labels, and legends.
| | 00:09 |
Forutnately, MATLAB makes all these
things easy to add.
| | 00:14 |
Returning to the S&P 500 graph from the
previous video, I'm going to put my
| | 00:18 |
function in a script and then add lines,
labeling each of these axes.
| | 00:22 |
To do this, I click on new script and
then I'm just going to copy and paste the
| | 00:28 |
command previously used to create the
graph, it should be in your command history.
| | 00:36 |
The syntax for each of the access label
is x label, y label or z label, followed
| | 00:43 |
by the text in single quote.
So we would have x label of date, y label
| | 00:48 |
of close and z label of volume.
When the script is run, the graph will be
| | 00:56 |
displayed again, but this time it will
have the axes with labels.
| | 01:02 |
When the script is run, the graph will be
displayed again, but this time the axes
| | 01:06 |
will be labeled.
Adding the title works the same way using
| | 01:09 |
the Title Command.
Simply type, title{'S&P500'} to add the
| | 01:14 |
text to the top of the graph.
Finally, adding a legend to the graph
| | 01:22 |
uses the Legend function.
Here the syntax is to put a string for
| | 01:26 |
each data set separated by commas.
The strings will display next to asymbol
| | 01:31 |
for their appropriate data on the plot.
In this case, I'll add the line, legend, S&P500.
| | 01:36 |
Since their is only one data set I don't
need to set separate this with commas.
| | 01:44 |
Running this will create a box on the
graph that displays the text and the
| | 01:47 |
function along with the color of the line
of that data set.
| | 01:51 |
Notice that each of these lines is added
after the creation of the graph with no
| | 01:55 |
other references to link them to the plot
itself.
| | 01:57 |
This occurs because MATLAB essentially
considers the most recently plotted graph
| | 02:02 |
to be the active graph and all changes
will affect it.
| | 02:05 |
Although it's not technically required to
have the lines for axis, titles and
| | 02:09 |
legends directly after the creation of
the plot.
| | 02:12 |
It helps keeps thing organized and
prevents you from accidentally creating
| | 02:15 |
another graph before the first is fully
defined later on.
| | 02:19 |
Once you have the graph created you can
also add additional annotations here.
| | 02:23 |
One of the most useful annotations you
can add is to indicate a single relevant point.
| | 02:29 |
So in this graph I'm going to rearrange
it so it is displaying the close versus
| | 02:34 |
the date.
And then we can notice that at a certain
| | 02:37 |
point on the graph it goes down very
sharply.
| | 02:40 |
This corresponds to the financial crisis
in 2008 and its a point that we might
| | 02:45 |
want to point out to people if we were
doing a presentation on this graph.
| | 02:49 |
To select this point, click on the Data
Cursor tool and then click and drag on
| | 02:55 |
the graph, have a point appear indicating
exactly where you're looking at on the graph.
| | 03:00 |
If we drag the marker to this relevant
point, we can immediately see what each
| | 03:04 |
of the values were for that date.
If, as you're writing a script, you ever
| | 03:09 |
lose track of which graph is defined at
which point in you script, you can get
| | 03:13 |
the current figure handle with the gcf
command.
| | 03:17 |
Simply typing the line h=gcf with no
parameters or turn an integer
| | 03:23 |
corresponding to the number of the figure
displayed in the top bar of the figure window.
| | 03:27 |
For instance, in this case if we run it
we would get that h equals 1 because this
| | 03:33 |
is figure 1.
If there is no current active figure, a
| | 03:36 |
new one will be created and a blank
figure window will appear.
| | 03:40 |
When you're satisfied with how your graph
looks you can choose to save it.
| | 03:43 |
To save your graph click on the File drop
down menu and choose Save As.
| | 03:49 |
The very first time you open this up, it
will ask you if you want to save it as a
| | 03:53 |
MATLAB figure.
But if you choose a different type and
| | 03:56 |
save your graph as that, it will remember
your default image in the future.
| | 04:00 |
In this case, the default image is a JPG
file, which is a fairly common image file
| | 04:05 |
that can be inserted into a wide variety
of different documents.
| | 04:08 |
You can also choose from several other
types of files, including a Bitmap file,
| | 04:13 |
a PDF file, or a PNG file.
When you're satisfied with your file
| | 04:18 |
choice, click on Save.
And you will now have the file ready to
| | 04:21 |
be inserted into any presentation you
want.
| | 04:24 |
As you can see the graph is much easier
to understand.
| | 04:27 |
| | Collapse this transcript |
| Working with images| 00:00 |
When most people hear the term "matrix",
they don't tend to associate it with an
| | 00:04 |
image However, a matrix is precisely what
an image is.
| | 00:07 |
It's a two-dimensional collection of
values corresponding with pixels of color.
| | 00:13 |
As a result, MATLAB can actually import
an image just as it would an Excel spreadsheet.
| | 00:19 |
And can work with the data within as if
were purely numerical.
| | 00:23 |
To import an image, double-click on it in
your active folder.
| | 00:26 |
In this example, I'll import the file
named building.jpg in exercise files.
| | 00:33 |
These specific format of an image matrix
depends on the file format itself.
| | 00:38 |
But the most common format is RGB, where
each pixel contains three values
| | 00:43 |
corresponding to a saturation in red,
green and blue colors.
| | 00:48 |
As a result, MATLAB models this image as
a three dimensional matrix.
| | 00:52 |
The first two dimensions correspond to
the height and width of an image, and the
| | 00:56 |
third is always equal to three, so that
each pixel can have the correct three
| | 01:01 |
values stored in it.
Modifying an image is a complicated
| | 01:05 |
mathematical problem that is beyond the
scope of this course, but MATLAB treats
| | 01:10 |
image data as nothing but a number.
So any formula that works with pixels of
| | 01:15 |
the available data type will function as
expected in MATLAB.
| | 01:19 |
For instance, one very simple
modification we could do would be to
| | 01:23 |
remove all of the red pixels from this
image.
| | 01:27 |
To do that, we can type in building of
colon, comma, colon, comma 1 equals
| | 01:35 |
zeroes of 685 comma 1,024.
Basically, what this does is it takes the
| | 01:43 |
first slice of the building matrix, which
corresponds to the red values, and sets
| | 01:48 |
it equal to a zero matrix of the same
size.
| | 01:51 |
When we run this, and then type in image
of building to display the building, we
| | 01:57 |
can see that it now displays completely
green and blue with no red color at all.
| | 02:03 |
A few simple functions that work well
with MATLAB images are Image, Image SC,
| | 02:07 |
ImageRead, and ImageWrite.
The image function displays your data as
| | 02:13 |
an image, which is useful as a way to see
how the image changes as a result of any
| | 02:17 |
modifications made in the context of a
script.
| | 02:21 |
Imagesc also displays an image, but it
first scales the colors of the image to
| | 02:26 |
include the full range of colors
available.
| | 02:30 |
This is roughly equivalent to increasing
the contrast of an image.
| | 02:33 |
And it's useful as a way of insuring that
the image will display correctly on
| | 02:37 |
different monitors with different color
schemes.
| | 02:41 |
The imageread and imagewrite commands do
not display an image directly, instead
| | 02:46 |
they allow you to load an image from a
file or store on MATLAB Matrix as an
| | 02:50 |
image, respectively.
This saves you from having to manually
| | 02:56 |
load and store images before and after
running a script.
| | 03:00 |
With these tools, working with images in
MATLAB should be a lot less mystifying.
| | 03:04 |
| | Collapse this transcript |
| Creating responsive programs| 00:00 |
As a highly technical formula based
computing language.
| | 00:04 |
MATLAB is perhaps less dependent on user
input then languages like Java or C++
| | 00:10 |
that are often based around the gooey.
However, it still has several important
| | 00:15 |
commands that can be used to wait for and
process user input.
| | 00:19 |
For this video we'll use the responsive
practice dot m file and exercise files.
| | 00:25 |
This is a simple script that calculate a
number of sample statistic from a set of
| | 00:30 |
stock prices.
But right now everything is calculated immediately.
| | 00:33 |
Running a function will immediately
output a list of all of the sample
| | 00:38 |
statistics including a plot.
It is more user friendly though to
| | 00:43 |
calculate one result at a time, waiting
for user input between each one.
| | 00:48 |
The simplest function that can do this is
pause.
| | 00:51 |
This function, which requires no input
pauses your script to stop until the user
| | 00:56 |
presses any key.
Adding a numerical input in the form of
| | 01:00 |
pause parentheses and then a number
causes the program to wait for that
| | 01:05 |
number of seconds and then continue on
its own.
| | 01:08 |
Pausing can also be disabled globally
through the command pause off and then
| | 01:13 |
re-enabled through the pause on command.
Let's add a pause command in front of
| | 01:18 |
standard deviation of stocks and then add
a pause three command in front of the median.
| | 01:27 |
When the script is run the script will
calculate the mean, wait until the users
| | 01:32 |
presses a key, calculate the standard
deviation, wait three seconds.
| | 01:36 |
And then continue with the rest of the
program.
| | 01:39 |
The input command is a slightly more
complicated way of waiting for user response.
| | 01:44 |
This command has a syntax input of a
prompt in single quotes where the prompt
| | 01:49 |
is the string that will be displayed on
the command line when the command runs.
| | 01:53 |
It then waits for the user to type input
into the window and press Enter before continuing.
| | 01:58 |
The input is returned by the input
function so it can then be stored in a
| | 02:02 |
variable by writing a line of the form
result equals input of prompt.
| | 02:08 |
For instance, going back to the
responsive practice editor, I'll add the
| | 02:12 |
line true mean equals input of test mean
within single quotes before the mean
| | 02:18 |
squares error test.
Then running the function will have the
| | 02:22 |
user press any key, wait three seconds
and then ask the user for a guess at the
| | 02:28 |
true mean.
And then run a mean squared errors test
| | 02:31 |
based on that guess instead of always
using 1200.
| | 02:35 |
MATLAB automatically attempts to evaluate
the entered text as a normal command,
| | 02:40 |
which means that users can reference
variables in the workspace, call
| | 02:44 |
functions or use any form of normal
arithmetic in their input.
| | 02:48 |
MATLAB will automatically detect the type
of the data created by the input and then
| | 02:53 |
assign the variable to that type.
If you don't want the user to run
| | 02:57 |
commands you can modify the input
statement to read input of the prompt
| | 03:01 |
comma s in single quotation marks.
This tells MATLAB to interpret whatever
| | 03:07 |
the user types as a string literal
without evaluating expressions.
| | 03:11 |
This means that the variable to which the
input is assigned will now be a string.
| | 03:16 |
So if you wanted to use that variable as
a number later on in your function.
| | 03:20 |
You would need to use the num2str command
on the variables.
| | 03:24 |
| | Collapse this transcript |
| Editing variables manually| 00:00 |
Writing, debugging, and polishing scripts
to carry out any necessary calculations,
| | 00:05 |
is one of the primary uses of Matlab, but
it's not the only one.
| | 00:09 |
Sometimes there might a single problem,
that only has to be solved, one time in
| | 00:14 |
one specific way, and it wouldn't make
sense to write and test the script line
| | 00:19 |
by line to solve it.
In these situations it's worthwhile to
| | 00:23 |
understand how to manually edit and
manipulate variables from within the
| | 00:27 |
command window.
In this video I'll use the daily data.csv
| | 00:31 |
and building .jpg files as examples.
So let's import those now (BLANK_AUDIO).
| | 00:47 |
We will end up with 4 different
variables.
| | 00:50 |
3, 2,515 by 1 vectors containing closed
prices, volumes and dates for the S&P 500.
| | 00:57 |
And 1, 685 by 1,024 by 3 matrix
Containing RGB values for each of the
| | 01:04 |
pixels in the building image.
The easiest way to edit a variable
| | 01:08 |
directly is to double click on it.
Double clicking on any of the stock
| | 01:12 |
variables will bring up a table
containing all of their values in a list.
| | 01:16 |
For a matrices with more than one column,
the additional columns will be displayed
| | 01:20 |
here as well.
From within this view, you can edit any
| | 01:23 |
value in the matrix simply by double
clicking on it.
| | 01:27 |
Changing the number stored in the cell
and then pressing enter.
| | 01:31 |
This is an especially effective editing
method for simple variables such as
| | 01:36 |
scalars and small vectors.
Obviously for large matrices, writing an
| | 01:40 |
algorithm will be much faster than
manually changing a variable.
| | 01:44 |
Now let's try to edit the image matrix.
When this variable is opened, Matlab will
| | 01:50 |
not display the data.
Instead it will display an error message
| | 01:54 |
saying that the variable size is too
large to be summarized.
| | 01:58 |
The variable view will also not allow
editing if the variable is more than 2 dimensional.
| | 02:04 |
Generally this isn't a problem because
it's not practical to edit a variable
| | 02:08 |
with more than 3 dimensions or 524,288
elements manually.
| | 02:14 |
However, if you know that you need to
edit only a certain element, you can edit
| | 02:18 |
just that element by typing tempvar
equals the variable name, x, y, z, and so
| | 02:25 |
on, depending on the dimensions.
The x, y, and z values are the indices of
| | 02:31 |
the matrix, and they can be either
scalars, if you want a single value, or
| | 02:36 |
ranges of numbers if you want a
collection of values.
| | 02:39 |
You can then edit tempvar in the editor
window as normal and return its values to
| | 02:44 |
the original variable by reversing the
equation and typing the variable name of
| | 02:49 |
those same indices or ranges equal
tempvar.
| | 02:52 |
For instance, if I wanted to chance just
the blue values in the center of the
| | 02:56 |
building image, I could type tempvar
equals building of 300-350, 500-550, 3.
| | 03:08 |
And then double click on temp far to open
it and edit it those values manually.
| | 03:13 |
For this example the change I'll make is
that temp far equals 0's of 51,51.
| | 03:22 |
So we just set all of the values to zero.
I can now reassign these values back to
| | 03:27 |
the building matrix by reversing the
earlier command and typing building of
| | 03:33 |
300 to 350, 500 to 550, 3 equals tempvar.
This would be a good example of a place
| | 03:44 |
where you might want to use a semicolon,
as you can see that forcing all of these
| | 03:49 |
values to display in the command window
takes a lot of extra time.
| | 03:52 |
When the matrix is displayed as an image
once more by typing Image of building.
| | 04:00 |
It's easy to see the change.
The main advantage of a script over
| | 04:04 |
command lines in MATLAB is that it can be
saved and run again later.
| | 04:08 |
However, it is possible to save the
states of the variables that you're
| | 04:11 |
working on even without a script.
Click on Save Workspace in the Variable
| | 04:16 |
tab and choose the names for your
workspace.
| | 04:19 |
This will save a record of the exact
values of all of your variables at this
| | 04:23 |
point as .mat file.
Double clicking on the file later on will
| | 04:30 |
then recreate those variables with
exactly the same values.
| | 04:33 |
It will not change or delete any other
variables in the workspace, but it will
| | 04:38 |
override any new values to which your
saved variables had been assigned.
| | 04:43 |
With these tools, MATLAB makes it easy to
work through a problem quickly and
| | 04:47 |
efficiently without worrying about
writing a permanent script or a function.
| | 04:51 |
| | Collapse this transcript |
|
|
5. External ToolboxesWhat are MATLAB toolboxes?| 00:00 |
Like many other programming languages,
MATLAB has a wide variety of extensions
| | 00:05 |
and program libraries available for use
in a diverse field of applications.
| | 00:09 |
These libraries called toolboxes in
MATLAB range from programs that make
| | 00:14 |
common calculations simpler to program
sets that allow MATLAB to calculate
| | 00:18 |
results in completely different ways.
Each tool box is integrated with the main
| | 00:23 |
MATLAB interface and provides libraries
of default functions that can be used for
| | 00:28 |
a variety of applications.
Some tool boxes such as the Symbolic Math
| | 00:32 |
Tool box also includes separate apps and
even separate programming languages.
| | 00:37 |
These can be used to extend the
functionality of MATLab to merge
| | 00:40 |
functions written in other languages and
provide additional tools for user
| | 00:44 |
interfaces, graphics and so on.
All of the MATLab tool boxes are
| | 00:49 |
available for purchase on the mathworks
website.
| | 00:52 |
As well as being purchased separately,
varying subsets of tool boxes are also
| | 00:56 |
bundled into different MATLAB products.
For instance, the student version of
| | 01:01 |
MATLAB contains ten of the toolboxes that
would be most relevant to college level
| | 01:05 |
engineering, mathematics, science, and
finance.
| | 01:08 |
If you're not sure which toolboxes are
installed on your version of MATLAB, you
| | 01:12 |
can display them by typing ver into the
command window.
| | 01:16 |
This will list all individual products
and their respective versions.
| | 01:20 |
Let's dig into the most common tool boxes
now.
| | 01:22 |
| | Collapse this transcript |
| Statistics Toolbox| 00:00 |
Let's take a look at the MATLAB
Statistics toolbox.
| | 00:03 |
This toolbox contains a number of
features of functions specifically
| | 00:08 |
designed to work with regressions,
summary statistics and probability.
| | 00:12 |
This slide displays some of the most
important additions.
| | 00:15 |
All the regression techniques in this
toolbox revolve around the linear model class.
| | 00:20 |
A linear model is an object comprising of
training data, a model description,
| | 00:25 |
diagnostic information and fitted
coefficients for linear regression.
| | 00:30 |
The most commonly used method within this
class is the LinearModel.fit method.
| | 00:34 |
Note that this is a class rather than a
script or a function so it defines a
| | 00:43 |
completely separate object.
This object then has specific
| | 00:47 |
subfunctions and scripts that will only
work on objects of that type.
| | 00:52 |
And they are called using this syntax we
display here with the class name.the
| | 00:58 |
model name and then the usual inputs for
the model.
| | 01:03 |
The LinearModel.fit command causes it to
display a linear regression model with
| | 01:09 |
coefficients for the intercept and slope
of the function.
| | 01:13 |
It will also calculate the standard
errors, t statistics, and p values at the
| | 01:18 |
same time.
So you can tell whether or not the model
| | 01:21 |
is significantly different from zero.
Below these results, MATLAB lists summary
| | 01:26 |
statistics including the r squared and p
value for the model.
| | 01:30 |
There are several different types of
linear regression techniques including
| | 01:35 |
linear, nonlinear, robust and ridge
techniques.
| | 01:39 |
So this is just that toolbox is not
limited to a simple OLS regretion.
| | 01:43 |
There are dozens of methods within this
class that can be accessed through the documentation.
| | 01:50 |
But for now let's just look at one other
method.
| | 01:53 |
Plot.
The plot method can be used on normal
| | 01:56 |
data with the syntax that we say in
earlier videos.
| | 02:00 |
But the linear model class overloads this
model class for convenience.
| | 02:04 |
If I type in plot of model MATLAB will
display the data set on which the model
| | 02:09 |
is based as well as the best fit line and
the confidence interval for the line on
| | 02:15 |
the graph.
It also automatically generates a title
| | 02:18 |
access labels and legend for the graph.
The Statistics Toolbox include many other
| | 02:24 |
functions and scripts but the most
important thing is that all of these new
| | 02:28 |
options are integrated within MATLAB
itself.
| | 02:31 |
You can use each of these new functions,
classes and so on with the exact same
| | 02:37 |
syntax as normal MATLAB functions.
| | 02:39 |
| | Collapse this transcript |
| Symbolic Math Toolbox| 00:00 |
Much of the computation in MATLAB
revolves around single specific cases.
| | 00:05 |
Certain numerical inputs are provided to
a function and it responds with a
| | 00:09 |
numerical output.
The Symbolic Math Toolbox expands this to
| | 00:13 |
include more abstract and general
computations.
| | 00:17 |
Rather than calculating a single solution
to an equation, the symbolic math toolbox
| | 00:22 |
allows you to input an equation and have
MATLAB solve it analytically to provide
| | 00:28 |
the general solution.
Aside from providing more theoretically
| | 00:31 |
useful results, this also eliminates
rounding errors and other side effects of
| | 00:36 |
finite computational power.
To designate a variable as symbolic use
| | 00:40 |
the sym function.
For instance if you type in x equals one
| | 00:42 |
third normally MATLAB will set x to be
the appromixate decimal represenation of
| | 00:51 |
one third which is 0.333 and so on.
On the other hand if you type in x equals
| | 00:59 |
sym of one third then MATLAB sets x equal
to precisely the fraction 1 over 3.
| | 01:06 |
It takes substantially longer to compute
operations on symbolic variables.
| | 01:11 |
But there is guranteed to be no rounding
error and in some cases having an answer
| | 01:16 |
that is a fraction can be more useful
than a long decimal.
| | 01:20 |
To designate a function as symbolic use
the symfun function.
| | 01:27 |
The syntax here is symfun of
function,inputs.
| | 01:32 |
This will define a general function that
takes in the given inputs and combines
| | 01:37 |
them according to the function to produce
an output.
| | 01:40 |
Of course this behavior could be
duplicated by simply defining a MATLAB
| | 01:44 |
function that takes in those inputs and
gives that output.
| | 01:48 |
But there is an important advantage to
using a symfun.
| | 01:52 |
It is stored as a variable not as a
separate file, which allows you to not
| | 01:57 |
only call it as a function but also use
it as an input term in another function.
| | 02:02 |
For example, if I wanted to define a
function that would take in the length,
| | 02:06 |
width and height of a rectangular prism
and return the volume, I could define it
| | 02:11 |
as follows.
First, I designate the three variables to
| | 02:15 |
be used in the function by typing syms of
l, w and h.
| | 02:19 |
Then I define the function, volume equals
symfun of l times w times h, comma l, w
| | 02:29 |
and h as the inputs.
Now I have the function for volume.
| | 02:33 |
I call this function at anytime by typing
volume length width and height and MATLAB
| | 02:40 |
will return the correct answer.
The Symbolic Math Toolbox provides
| | 02:44 |
numerous other functions in it's library
that allow you solve this function.
| | 02:48 |
Reduce it's terms or otherwise
manipulated analytically.
| | 02:52 |
These features of the Symbolic Math
Toolbox make complicated calculations a
| | 02:57 |
lot easier.
And can save you enormous effort that
| | 03:01 |
would otherwise be spent calculating
indefinite integrals, solving for various
| | 03:05 |
variables or otherwise working with
non-numerical terms.
| | 03:08 |
| | Collapse this transcript |
| Optimization Toolbox| 00:00 |
Let's take a look at the Optimization
Toolbox.
| | 00:03 |
This add-on is designed to aid in the
estimation of variables and parameters in
| | 00:08 |
optimization problems such as
regressions.
| | 00:10 |
The Optimization Toolbox has a few
functions of it's own but it's main
| | 00:14 |
feature is a Graphical Optimization Tool,
which allows you to optimize a wide
| | 00:19 |
variety of equations, based on various
criteria.
| | 00:23 |
This Optimization Tool effectively
encapsulates all of the different
| | 00:27 |
optimization functions provided by the
toolbox and allows you to specify each of
| | 00:32 |
the parameter separately.
To access this application, type in
| | 00:35 |
optimtool in the command window.
The tool will then appear in a popup window.
| | 00:40 |
On the left-hand side, you were asked to
specify the solver type, algorithm,
| | 00:46 |
objective function, start point, and
constraints.
| | 00:49 |
The results will then display t the
bottom.
| | 00:52 |
The right-hand side contains additional
options that allow you to specify how the
| | 00:56 |
function runs.
For instance, if you're running a very
| | 00:59 |
slow function, you might change the
number of iteration to a lower number so
| | 01:03 |
that you get your result quicker.
For this example, I'm going to use the
| | 01:08 |
optimtool function script, which is
provided in exercise files as the
| | 01:13 |
objective function.
This is a relatively simple function that
| | 01:16 |
calculates a result based on three
independent variables.
| | 01:20 |
Graphing the function to find its
minimums would require a four dimensional
| | 01:24 |
graph, and calculating the derivative to
find the minimums analytically would also
| | 01:29 |
be quite difficult.
But, the Solver Tool can optimize these
| | 01:33 |
values easily.
In this case, the Solver Tool is fmincon,
| | 01:38 |
because the objective is to minimize the
residuals with the variables constrained
| | 01:42 |
to certain values.
The optimization function is an @ symbol
| | 01:48 |
followed by the name of our script or
@optimtoolfunction.
| | 01:52 |
Any start point is fine but for this
example I'll use one, one and one.
| | 01:58 |
The start point can be important if
you're dealing with a function with more
| | 02:02 |
than one minimum, because the
Optimization Tool can only find a local minimum.
| | 02:07 |
It can't guarantee it that it will find
the absolute minimum.
| | 02:11 |
For the linear inequality, the constraint
requires that vector a times the input
| | 02:16 |
vector be less than or equal to b, so if
I put in a is 111, z is 100 that means
| | 02:24 |
that x plus y plus z is less than 100.
Once this is done click Start to run the optimization.
| | 02:32 |
The results are displayed under Final
point and these values will give the
| | 02:35 |
lowest possible function value under the
given constraints.
| | 02:40 |
Here, we have that the first variable x
is equal to negative 0.208.
| | 02:46 |
The second variable y is equal to 7.525.
And the third variable, z, is equal to 92.683.
| | 02:56 |
All of these variables sum up to just
under 100.
| | 02:59 |
And they get the lowest possible value of
the function given those constraints.
| | 03:04 |
The last thing you might want to do is
see how the optimization occurred.
| | 03:09 |
Under the Options menu, scroll down to
the Plot Functions bar and check Function Value.
| | 03:15 |
And then run the optimization again.
With this selected, MATLAB will display
| | 03:20 |
the function value after each iteration.
So you can easily see how changing the
| | 03:25 |
values cause the function value to drop
to it's lowest point.
| | 03:29 |
| | Collapse this transcript |
|
|
ConclusionWhere to go from here| 00:00 |
I hope you've enjoyed this Up and Running
with MATLAB course.
| | 00:03 |
So now what?
Where do you go from here?
| | 00:05 |
This course was designed to give you an
introduction to using MATLAB in a wide
| | 00:09 |
variety of field.
From numerical analysis to image
| | 00:12 |
processing, to finance and statistics.
Although the focus of this course was on
| | 00:17 |
MATLAB and use MATLAB syntax.
The basic principals behind manipulating
| | 00:21 |
and displaying large amounts of data are
clickable in many other programs.
| | 00:25 |
Once you know the basic syntax, the
MATLAB language is really just a
| | 00:29 |
collection of useful functions.
So the easiest way to use MATLAB in more
| | 00:33 |
advanced applications is simply to look
for the relevant function libraries and
| | 00:37 |
apply them as needed.
If you want to learn more about any of
| | 00:40 |
the applications of MATLAB, lynda.com
offers courses in 3-D animation, audio
| | 00:45 |
production, statistics, economics, image
analysis and more.
| | 00:48 |
Thanks for watching.
See you next time.
| | 00:50 |
| | Collapse this transcript |
|
|