You are on page 1of 101

Outline of Tutorial –(1)

• Introduction
• Getting Started
• Variables and Starting Basics
• Vectors and Matrices
• Basic Operations
• Script Files
Outline of Tutorial –(2)
• Basic Graphics Commands
• Other Useful Commands
• Final Words
Introduction – (1)
• MATLAB: MATrix LABoratory
• Created in 1970 by Cleve Moler
• Was (and still is) used extensively at
Stanford University and the University of
New Mexico
• Why? To make calculating the following things a lot
easier!
• Matrix Theory
• Linear Algebra
• Numerical Analysis
Introduction – (2)
• MATLAB is selected as a numerical analysis
tool over languages like C and Java because:
• Very EASY programming language
• Powerful graphics capabilities
• Very sleek and interactive interface
• Great for general scientific and engineering
computation
Outline of Tutorial –(1)
• Introduction
• Getting Started
• Variables and Starting Basics
• Vectors and Matrices
• Basic Operations
• Script Files
• Function Script Files
Getting Started – (1)
• Method #1:Available in Lab computers
• Method #2:If you don’t feel like using the
computers at school, you can install your own
copy of MATLAB on your PC or laptop
• There are many ways to obtain your own copy:
• Obtain it from : http://www.mathworks.com
• http://ryerson.ca/ccs/services/software/math.html
• https://vapps.ryerson.ca
Getting Started – (3)
• What happens next!?
• MATLAB Interface: >> means it’s ready for input from
you
Outline of Tutorial –(1)
• Introduction
• Getting Started
• Variables and Starting Basics
• Vectors and Matrices
• Basic Operations
• Script Files
• Function Script Files
Variables and Basic Commands – (1)
• One GREAT thing about MATLAB:
• MATLAB is a programming language that is
• dynamically typed… what does this mean?
• You can declare variables and initialize them without
• specifying what type they are
• MATLAB automatically figures this out for you, or you
can choose to manually override the type
• Example:
• C or Java way: int nikhil = 1, double jenny = 2
• MATLAB way: nikhil = 1, jenny = 2
Variables and Basic Commands – (2)
• When you want to assign something to a
variable, use the =sign
• When you assign something to a variable,
MATLAB initializes & automatically declares
it
• Guidelines for variable names:
• All must be single words, no spaces
• Must begin with a letter, numbers or the
underscore character ( _ )
• Variable names are case sensitive
• i.e nikhil is NOT the same as Nikhil
• i.e muffin is NOT the same as mUFfin
Variables and Basic Commands – (3)
• Some valid variable names:
• voltage
• valueOfR1
• Ron_and_Mauro
• _Alan2007_
• Some invalid variable names (why are these
invalid?):
• 123
• value of R1
• 3v
• X#*()$#$!!!
Variables and Basic Commands – (4)
• Left/Right panels:Current Directory / Workspace
• A) Shows you directory structure to access working
directory (more on this later)
• B) Shows you all of the variables that have been created
and can be accessed
• Command History
• Center: Command Prompt
• Enter commands and variable declarations here
• Commands without a semicolon ( ; ) echo
your command to screen
• Commands with a semicolon suppress that output
Variables and Basic Commands – (5)
• Can enter commands either:
• One at a time: The end of each command, press ENTER
(carriage return)
• Multiple commands in one line:
• Suppress echoing: Use semicolons to separate each command
on the line
• Enable echoing: Use commas ( , ) to separate each command
on the line
• Typing in a variable by itself and pressing ENTER
will redisplay the variable
• Entering a value, pressing ENTER, and not
assigning it to anything, the value will be
automatically assigned to a variable called
ans (answer)
Variables and Basic Commands – (6)
Variables and Basic Commands – (7)
• who command: Shows you all of the variables
created by you
• You can also check the workspace as well
• clear command: Clears all of the variables shown in
the workspace, and you start from scratch
• clc command: Flushes the command prompt
• Variables will still be in the workspace, but it clears the
command prompt screen
Variables and Basic Commands – (8)
Variables and Basic Commands – (9)
• Can also declare complex numbers too:
• Can add, subtract, multiply and divide
• You can use i or j to declare complex numbers
• Of course… you can also add, subtract, multiply
and divide normal numbers too!
• Too lazy to make a slide for it
• However, we’ll get into addition, subtraction,
multiplication and division in another way
later
Variables and Basic Commands – (10)
Variables and Basic Commands – (11)
• Command History window: Used to keep track of
the commands you ran recently
• You can also
double click on
any of the commands
to re-run them again
• You can also press
the up & down keys
to cycle through
the commands as
well in the command
prompt
Outline of Tutorial –(1)
• Introduction
• Getting Started
• Variables and Starting Basics
• Vectors and Matrices
• Basic Operations
• Script Files
• Function Script Files
Vectors and Matrices – (1)
• Unless otherwise defined, MATLAB treats ALL
variables as 2D matrices… how is this possible?
• Arrays and Vectors: N x 1or 1x N matrix
• Single value: 1x 1matrix
• Why does MATLAB decide to handle it this way?
• You’ll see later that handling variables as matrices makes
things A LOT faster and easier to work with
Vectors and Matrices – (2)
• How do you declare a vector / array in
MATLAB?
• C or Java way: int a[4] = {1, 2, 3, 4};
• MATLAB way:
• a = [1 2 3 4] – row vector
• Spaces mean to move to the next column
• a = [1 2 3 4].’ – (.’ operator means to transpose
a vector) - column vector
• a = [1;2;3;4] - column vector
• Semicolon means to move to the next row
• You do not have to specify how big the vector
is first before you make it
• Beauty of dynamically typed languages!
• MATLAB automatically figures out how big it is
Vectors and Matrices – (3)
• How do I access elements in a vector / array?
• C or Java way:
• int jenny = a[0];
• MATLAB way:
• jenny = a(1);
• NOTE!:
• No square brackets when accessing an element! Use
round brackets!
• Elements do not start at index 0, they start at index 1!
Vector and Matrices – (4)
Vector and Matrices – (5)
• How do I create a matrix in MATLAB?
• C or Java way: int a[4][4] = {{1, 2, 3, 4},
{5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14,
15, 16}};
• MATLAB way:
• #1: a = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13
14
15 16];
• #2: a = [1 2 3 4;
5 6 7 8;
9 10 11 12;
13 14 15 16];
Vector and Matrices – (6)
• How do I access elements in a matrix?
• C or Java way:
• int alan = a[2][3];
• MATLAB way:
• alan = a(3,4);
• What’s the difference here?
• No separate brackets for each dimension
• Comma is used to separate the dimensions
• Remember: 1st parameter is the row, 2nd parameter is the
column
Vector and Matrices – (7)
• Here’s something to mess you up… how do I
access a range of values in a matrix?
• Suppose I had a matrix already created called
ray
• How do I get all of the elements in the 1st row?
• C or Java way:
• int i;
for(i = 0; i < 4; i++)
ray[i] = a[0][i];
Vectors and Matrices – (8)
• MATLAB way:
• ray = a(1, 1:4);
• ray = a(1, :);
• What’s the difference here?!
• NO for loop!
• The colon ( : ) operator is used to access a range of values
• 1: 4 means a range from 1through 4 for a dimension
• : by itself means give me all possible values in a dimension
• Doing 1: 4 in the 2nd parameter means give me columns 1
through 4
• Doing : in the 2nd parameter means give me all of the
columns!
Vectors and Matrices – (9)
Vectors and Matrices – (10)
• Some more examples:
• sally = a(2,3);
• sally = a(1:3,3:4);
• sally = a(:, 1:3);
• sally = a(2:4,:);
Vectors and Matrices – (11)
• Here’s a curve ball!
• Joe = a(:,:);
• Joe = a;
• What does this mean? Copy the entire matrix, a,
and assign it to Joe
• You can also do the 2nd line too. It’s exactly the same
meaning
Vectors and Matrices – (12)

• Example Time!
Vectors and Matrices – (13)
Vectors and Matrices – (14)
Vectors and Matrices – (19)
• General Form:
• new_array = first_value : increment
: last_value
• Make note of the colons ( : )!
• first_value: The first value in the new vector
/ array
• last_value: The last value in the new vector
/ array
• increment: The step size
• If you don’t include this value, it is
automatically assumed to be 1
Vectors and Matrices – (20)
• Examples:
• jenny = 0 : 2 : 10;
• eman = 3 : 3 : 30;
• ron = 1 : 10;
• mauro = 2.0 : -0.2 : 0.4;
• 1st line: Creates a 6 element vector
• jenny = [0 2 4 6 8 10];
• 2 nd line: Creates a 10 element vector
• eman = [3 6 9 12 … 27 30];
Vectors and Matrices – (22)
• 3rd line: Creates an 10 element vector
• ron = [1 2 3 … 9 10];
• 4 th line: Creates a 8 element vector
• mauro = [2.0 1.8 … 0.6 0.4];
• Pretty easy don’t you think!?
• Remember how I told you about that colon
operator?... Well, here you go!
• To do this in C and Java, it requires a bit more work.
Vectors and Matrices – (23)
• Some useful matrix and vector / array commands
• eye(n): Creates an n x n identity matrix
Vectors and Matrices – (24)
• Some useful matrix and vector / array
commands
• ones(n,m): Creates an n x m matrix full of ones

• ones(1,n) or ones(n,1): Creates an array /


vector that has n elements, full of ones
Vectors and Matrices – (25)
• Some useful matrix and vector / array
commands
• zeros(n,m): Creates an n x m matrix full of zeros
Vectors and Matrices – (26)
• Last important note:
• MATLAB evaluates expressions to the right of
the equals sign first
• After, it assigns this result to the variable to the left of
the equals sign
• Here’s an example:
sum = 2;
sum = sum + 3;
• What happens here? sum gets assigned the value of 2
first, then it gets added with 3, and stored back into
sum
• …and that’s it for this section…
Outline of Tutorial –(1)
• Introduction
• Getting Started
• Variables and Starting Basics
• Vectors and Matrices
• Basic Operations
• Script Files
Basic Operations – (1)
• Let’s assume the following:
• A and B: Are matrices or vectors / arrays of
compatible dimensions
• Assume they can be added, subtracted, multiplied
and divided properly
• n is a scalar (single value number)
• Here’s a table that provides a good summary of all
of the basic operations you can perform on matrices
and vectors / arrays
Basic Operations – (2)

• Here, the elements in the matrices or vectors


/ arrays can be real or complex
• Addition and Subtraction will just add
and subtract two matrices normally
• For vectors, each corresponding component
gets added or subtracted
Basic Operations – (3)
Basic Operations – (4)
Basic Operations – (10)
• Here are some useful commands for matrices and
vectors / arrays:
• Assume that V is a vector of arbitrary length and M
is a matrix of arbitrary size
• len = length(V);
• Gives the number of elements the vector V has, and
stores it into len
• [rows cols] = size(M);
• Gives the number of rows and columns and stores them
into rows and cols respectively
• Don’t worry about the square braces for now, we’ll deal
with them later.
Basic Operations – (11)
• sum(V): Returns the sum of all elements contained in
vector V
Basic Operations – (12)
Outline of Tutorial –(1)
• Introduction
• Getting Started
• Variables and Starting Basics
• Vectors and Matrices
• Basic Operations
• Script Files
Script Files – (1)
• So far, you’ve seen that MATLAB can accept and
execute commands interactively through the
command prompt
• …what happens if you’ve got A LOT of commands to
execute?
• Think C or Java: You put all commands or syntax
into a file and execute that file.
• You can do this with MATLAB, and you don’t have
to input all of the commands individually.
Script Files – (2)
• This kind of file is called a script file or M-file
(M for MATLAB!)
• You place all commands you want to execute in a file
with extension .m at the end, and you run the script
file
• MATLAB will run all of these commands in sequence for
you
• To execute a script file, make sure you set
the working directory to be where the script
file is located (remember I said we’d get back
to this earlier?)
Script Files – (3)
Script Files – (4)
• MATLAB has a M-file editor that you can use
where you can create your scripts
• You can also use any other word processing editor. Just
make sure the extension of the file is .m
• It’s got:
• Some nice colour coding features
• Debugging Tools
• Interoperability with the MATLAB command prompt
Script Files – (5)
Script Files – (6)
• Once a script file has been created, type in the
name of the file (without the .m) in the
command prompt to execute the script
• Make sure you set the proper working directory!
• When you execute a script file, all of the
variables created in the script file get stored in
the workspace for future use
• Let’s do an example:
• Let’s make the factorial example into a script file
Script Files – (7)
Script Files – (8)
Script Files – (9)
• The great thing about script files is that commands can
be re-executed without having to enter them all
again!
• All you have to do is modify parts of the script file to
give you the result you want
• The script file is now set to compute 4!What if I
wanted to do 9!, or 12!, or 5! ?
• Just change the n parameter accordingly
Outline of Tutorial –(1)
• Introduction
• Getting Started
• Variables and Starting Basics
• Vectors and Matrices
• Basic Operations
• Script Files
Outline of
• Introduction
Tutorial –(1)
• Getting Started
• Variables and Starting Basics
• Vectors and Matrices
• Basic Operations
• Script Files
• Function Script Files
Function Script Files – (1)
• So, you’ve seen how script files work
• So what are function script files?
• Think Java: These are methods
• You send input variables into a function
• Difference: You don’t have to define what the variable types are.
Remember: DynamicallyTyped!
• The function performs MATLAB commands with these
input variables
• The function returns output variables
• Difference: You can return more than one variable!
• You don’t have to define the variable type either!
• Unlike C or Java, you do not require return statements to
return variables
• All you have to do is assign something to the variable, and that’s it.
Function Script Files – (2)
• Why would you want function script files?
• Instead of changing some parts of a script file, you can
do these changes by providing different variables to
the input of the function
• There may be a case where when you run a script, you
don’t want variables created in the script to be saved
to the workspace
• Function scripts only communicate with
the MATLAB workspace with:
• The variables that you pass to it
• The variables that get sent to the output after it’s
finished
Function Script Files – (3)
• What does this mean?
• Any variables you create within the function will be
discarded after the function has finished executing
• This is what we call local scope
• How do we create a function script file?
• Pretty much the same as a normal script file
• .m as the extension to the file
• Remember, with a script file, all you had to do was
enter in the commands in sequence
Function Script Files – (4)
• However, there are two differences between a
script file, and a function script file
• The file name of the function has to be the same as the
function itself
• The first line of a function script file must be the
following:
function [output1, output2,…] =
function_name(input1, input2, …)
Function Script Files – (5)
• The function keyword means that this script
file is a function script file
• input1, input2, …represents the input
variables going into the function
• output1, output2, …represents the output
variables going into the function
• You may have noticed that there are square
braces ( [ ] ) surrounding the output variables
in the function header
• In order to return more than one variable, MATLAB puts
all of the variables into on e vector and returns this
vector, hence the [ ] …
Function Script Files – (6)
• Use the % operator to put in comments
• If you want to perform the modulus, use the mod function
• mod(x,y) == x % y in C or Java
• If you want to comment out a block of code, do the
following:
%{

commands that are commented out

%}
• When you’re coding a function script file, it’s a good idea to
put an author’s block at the beginning of the file, that
tells someone how the function works, what inputs you
need, what outputs come out, and how to use it
Function Script Files – (7)
• Some examples of function script files that you have seen
already:
• eye(n)
• Input: number n, n >0
• Output: nx n identity matrix
• prod(V), prod(M)
• Input: Vector V or Matrix M
• Output: A number or a vector
• sum(V), sum(M)
• Input: Vector V or Matrix M
• Output: A number or a vector
• max(V), max(M)
• Input: Vector V or Matrix M
• Output: A number or a vector
• min(V), min(M)
• Input: Vector V or Matrix M
• Output: Anumber or a vector
Function Script Files – (9)
• So now with this, let’s go back to our factorial
example and make this a function script file
• What do we need to do in order to make this
a function script file?
• Think back to the two differences that I said
earlier about script files and function script files

7
Function Script Files – (10)
Function Script Files – (11)
Outline of Tutorial –(1)
• Introduction
• Getting Started
• Variables and Starting Basics
• Vectors and Matrices
• Basic Operations
• Script Files
• Function Script Files
Outline of Tutorial –(2)
• Flow Control
• Basic Graphics Commands
• Other Useful Commands
• Final Words
Flow Control – (1)
• You’ve seen this in C or Java many times
• Flow control allows your script or function script
file to have decision making abilities
• …understand what I mean? If you don’t, MATLAB
supports the following common flow control
methods
• for loop
• while loop
• if-else & else-if statements
• switch-case-otherwise statements
• …now you see what I mean right?
Flow Control – (2)
• for loops allow a group of commands to be
executed a predetermined amount of times
• This loop has the following structure:
for i = any_array

commands to be executed

end
• any_array is any valid array
• Can be any row or column vector
Flow Control – (3)
• How this for loop works is as follows:
• 1st iteration, i = any_array(1), then execute
commands
• 2nd iteration, i = any_array(2), then execute
commands …
• n th iteration, i = any_array(n), then execute
commands
Flow Control – (4)
• First Example: for loop in uniform steps
• f = 1;
for i = 1:n
f = f*i;
end
• Here, we’re computing our factorial function, but
with the use of a for loop
• i is assigned 1for the 1st iteration, 2 for the
2nd iteration, and n for the n t h iteration
• For each iteration, we take the previous value of
f and multiply by the current value of i
Flow Control – (5)
• Second Example: for loop in non-uniform steps
• val = 0;
array = 1 : 20;
for i = [1 4 8 9 10 2 5]
val = val + array(i);
end
• Here, we’re computing the sum of random elements in an array and
storing them into val
• Take a close look at what I did in the for loop
• The 1st iteration, i = 1, the 2nd iteration, i = 4, the 3rd
iteration, i = 8, and so on
• Pretty cool eh!? You don’t have to have uniform steps in
your for loops!
Flow Control – (6)
• while loops let you execute a group of
commands indefinitely until a condition is met
• The structure for this loop is as follows:
while expression

commands to be executed

end
Flow Control – (7)
• The commands between the while and the
end statements are executed until
expression is evaluated as false, or a zero
(0) value
• You usually use relational or equality operators in the
expression statement of the while loop
• A relational or equality expression is assigned a
value of 1if it’s true, and 0 if it’sfalse
Flow Control – (8)

• Everything here is the same as C and Java,


except for the not equals to operator. MATLAB
has it as ~=, and C or Java has it as !=… be
careful not to mix these up!
Flow Control – (9)
• if-else & else-if statements help you execute blocks
of commands when some condition is true
• Here’s the syntax for it… but I’m sure you already know this
if exp_1

commands to be executed if exp_1 is true

elseif exp_2

commands to be executed if exp_2 is true

elseif exp_3

commands to be executed if exp_3 is true

else

commands to be executed if none of the above is true

end
Flow Control – (10)
• Note the following:
• elseif and else operators are optional
• You can have if statements by themselves as
well without the above operators
Flow Control – (11)
• switch-case-otherwise statements are a
special case (no pun intended) of the if-else
& else-if statements
• You choose between a finite number of choices;
each choice consists of a block of commands to
be executed
• If the choice you make is none of the choices
provided in this statement, we execute a
default (otherwise) code block
• …so this is what this kind of statement looks
like:
Flow Control – (12)
switch expr
case value1,

commands to be executed if expr equals value1

case value2,

commands to be executed if expr equals value2


otherwise,

commands to be executed if the value of expr is
not equal to any of the above values

end
• You usually use switch statements when you want your program to run
differently, based on the input parameters that are given to your function script
file
Outline of Tutorial –(2)
• Flow Control
• Basic Graphics Commands
• Other Useful Commands
• Final Words
Basic Graphics Commands – (1)
• MATLAB provides a variety of sophisticated
techniques for presenting and visualizing
data
• Also, MATLAB makes it very easy to plot data!
• I have never used MS Excel ever again because
MATLAB makes it easy!
• The watered down version:
• Provide an array of values for each set of axes
• Run a function that plots things for you
• Run a few more commands that will make a grid, set the
title of the graph, the title of the axes and so on
Basic Graphics Commands – (2)
• 2D plotting: MATLAB makes this very easy!
• If x and y are arrays of elements that are the same
size, you can plot them using this data with the
following command:
plot(x, y);
• This will bring up a window plotting a graph of y vs. x
• To plot something simple, that’s just about it!
Basic Graphics Commands – (3)
• Here’s a basic example if you don’t believe me
• Let’s say I wanted to plot the line y = x
• Let’s choose 101 points between 0 to 10 in steps
of0.1
• Here’s the syntax I’d use:

…and that’s it!


• This is what the graph looks
like…
Basic Graphics Commands – (4)
Basic Graphics Commands – (5)

• If you want to plot multiple plots on a


single graph, you do the following:
plot(x1,y1,x2,y2,…,xN,yN);
• N is the number of plots you want to appear on the
single graph
• xi and yi are the points to the ith graph you
want plotted on the single graph
• The number of elements between
(x1,y1), (x2,y2), …(xN,yN) must all
be the same!
Basic Graphics Commands – (8)
Basic Graphics Commands – (10)
• So let’s say I wanted to add a title, add a grid, label
the axes and put up a legend, how would I do that?
Basic Graphics Commands – (12)
• grid puts a grid on the graph
• The spacing for the grid is automatically figured out
by MATLAB
• title(‘…’) lets your graph have a title
• xlabel(‘…’), ylabel(‘…’) labels the x and
y axes accordingly
• Put the labels inside the quotations
• Don’t forget the quotations ‘‘!
• legend(‘…’, ‘…’, …, ‘…’) produces
a legend, labeling what each plot is on the
graph
Outline of Tutorial –(2)
• Basic Graphics Commands
• Other Useful Commands
• Final Words
Other Useful Commands – (1)
• MATLAB has a great help facility, both through
its interface and online
• If you need help regarding how a certain command
works, type in the following in the command
prompt:
• help command
• command is the command you want to look up and
to see how it works
Other Useful Commands – (2)
• If you don’t know what a particular function is
called, you can use the lookfor command
• It’s called the following way:
• Look for command
• Where command is the function you’re looking for
• MATLAB searches all of its libraries that are related
to command
Other Useful Commands – (3)
• A list of all of the MATLAB commands you have invoked in
a session in the command prompt can be written into a file
with the diary command
• You call this command this way in the command prompt
diary diary_file
• diary_file is the name of the file where your commands
you invoked in that session will be stored
• If the file already exists, your commands in the current
session will be appended to the file
• Use diary off to turn off the diary command, and
diary onto reactivate it
Outline of Tutorial –(2)
• Flow Control
• Basic Graphics Commands
• Other Useful Commands
• Final Words
Final Words – (1)
• This tutorial provided you the basics of how to
use MATLAB and enough to get you started with
this course lab
• This tutorial, however, is not exhaustive
• There are still a lot of commands out there that
perform really cool stuff for you
• Consider taking some time to look at them and see
how cool MATLAB is
• Always use the help and lookfor
commands when you’re learning a new
function
• If all else fails, ask me!

You might also like