EXPERIMENT
8
Introduction to MATLAB
MECHATRONICS SYSTEM DESIGN
COURSE MECHANICS
Groups:
https://groups.yahoo.com/neo/groups/DE_34_MTS
All slides/assignments to be uploaded on the group –
please check mails at least once a day.
Submit Lab reports on the LMS before next lab. Late reports
shall not be entertained.
COURSE MECHANICS
Requirements for passing
Attend all lectures
Complete all assignments
Quizzes
Pre-requisites
Basic familiarity with programming
Revise Arrays, Structures in C
Outline
Basics of MATLAB
Introduction to the MATLAB Environment
Variables
Basic operations
Basic plotting
Visualization
Programming (conditional statements and loops etc.)
Simulink
Graphical User Interface
DIP Toolbox
Camera interface
Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
MATLAB
Stems from: MATrix LABoratory
Mathematical Verification of Concepts
– Algorithm development/prototyping
– Rapid ability to tweak and perform “what if” trials
– Visualize what an equation does or says
Engineering
– System Modeling
– Algorithm Development and Verification
– Implementation Validation
– Test Signal Generation and Results Analysis
Suffice it to say, MATLAB is a powerful software. And you will soon
find that out
Getting Started
Open up MATLAB for Windows
Through the START Menu
Through the Desktop Shortcut
Starting Command Window
Current directory
Workspace
Command Window
Command History
MATLAB Environment
Command Window
Use the Command Window to enter
variables and run functions and M-files
Command History
History, you can view previously
used functions, and
Copy and execute selected lines
MATLAB Environment
The MATLAB workspace
Consists of the set of variables
(named arrays) built up during a
MATLAB session and stored in
memory
Current working directory
Customization
File Preferences
Allows you to personalize your MATLAB experience
MATLAB Help
Command Line
Very well documented software
Help available on all
commands/functions
>> help
>> doc
Try this
>> help sin
Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
Numeric Variable Types
MATLAB is a weakly typed language
No need to define or declare a variable before it is used
Data Type Class Size (bytes)
Integers int8 1 byte
int16 2 bytes
int32 4 bytes
uint8, uint16, uint32 are unsigned versions
Floating point single 4 bytes
double 8 bytes
Boolean logical 1 byte
Character char 1 byte
Most variables you’ll deal with will be arrays or matrices of doubles or chars
Images are stored and manipulated as 2-D arrays of real numbers
Other types are also supported: complex, symbolic, etc.
Creating/Naming variables
To create a variable, simply assign a value to a name:
Take a look at your
var1=3.14 workspace, the variables
have been added
myString=‘hello world’
>> 34_mts = 3.4
Variable names Gives error
>> mts_34 = 3.4
first character must be a LETTER
Valid assignment!
after that, any combination of letters, numbers and _
CASE SENSITIVE! (var1 is different from Var1)
Try these commands
Built-in variables >> 1/0
>> -1/0
i and j can be used to indicate complex numbers >> 0/0
pi has the value 3.1415926… >> var_complex = 3 + 2i
ans stores the last unassigned value (like on a calculator)
Inf and -Inf are positive and negative infinity Try this
>> 6 + 3
NaN represents ‘Not a Number’ >> ans
>> 6 - 3
>> ans
Variables cont.
You can specify the type on
Tip: To view the list of variable
creation currently in workspace, try
>> who
var_int= int8(34)
or for more details
var_single = single(35.51) >> whos
For numbers, the default Try this
date type is double >> try_this = int8(44.5)
>> whos(‘try_this’)
var_default = 34.5 >> try_this
will create the variable of type
double
Scalars
A variable can be given a value explicitly
a = 10
Check MATLAB workspace, it now shows the newly created variable ‘a’
Or as a function of explicit values and existing variables
c = 1.3*45-2*a
Tip: To suppress output (i.e. not show results of
command on command window), end the line
suppressed = 66/2; with a semicolon.
Might speed up execution
Arrays
Like other programming languages, arrays are an
important part of MATLAB
Two types of arrays
(1) matrix of numbers (either double or complex)
(2) cell array of objects (more advanced data structure)
MATLAB makes vectors easy!
That’s its power!
Row Vectors
Row vector: comma or space separated values between
brackets
row = [1 2 5.4 -6.6];
row = [1, 2, 5.4, -6.6];
Command window:
Workspace:
Column Vectors
Column vector: semicolon separated values between
brackets
column = [4;2;7;4];
Command window:
Workspace:
Matrices
Make matrices like vectors
1 2
Element by element a
3 4
a= [1 2;3 4];
By concatenating vectors or matrices (dimension matters)
a = [1 2]; Note:
b = [3 4]; >> d = [a;b];
is the same as
c = [5;6]; >> d = [a
b];
d = [a;b];
e = [d c];
f = [[e e];[a b a]];
save/clear/load
Use save to save variables to a file
save myfile a b
saves variables a and b to the file myfile.mat
myfile.mat file in the current directory
Default working directory is
…\MATLAB\ (check using pwd)
Create own folder and change working directory to it
Use clear to remove variables from environment
Try this (keep monitoring
clear a b
the Workspace window ):
To clear all variables >> a = 2, b = 3, c
clear all = a*b
look at workspace, the variables a and b are gone >> whos
>> save my_var
Use load to load variable bindings into the environment >> clear all
load myfile
>> whos
>> load my_var
look at workspace, the variables a and b are back
>> whos
Can do the same for entire environment
save myenv; clear all; load myenv;
Exercise: Variables
Do the following 5 things:
Create the variable r as a row vector with values 1 4 7 10 13
Create the variable c as a column vector with values 13 10 7 4 1
Save these two variables to file varEx
clear the workspace
load the two variables you just created
>> r=[1 4 7 10 13];
>> c=[13 10 7 4 1];
>> save varEx r c Tip: If your screen is congested
>> clear all and you want to clean up
>> load varEx >> clc
Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
Basic Scalar Operations
Arithmetic operations (+,-,*,/)
7/45
(1+i)*(2+i)
1.1 – 0.1
Exponentiation (^)
4^2
(3+4*j)^2
Complicated expressions, use parentheses
((2+3)*3)^0.1
Multiplication is NOT implicit given parentheses
Try
>> 3(1+0.7)
Error!
>> 3*(1+0.7)
OK
Built-in Functions
MATLAB has an enormous library of built-in functions
Call using parentheses – passing parameter to function
sqrt(2)
log(2), log10(0.23)
cos(1.2), atan(-0.8)
exp(2+4*i)
round(1.4), floor(3.3), ceil(4.23)
angle(i); abs(1+i);
For Help on a function
>> help sqrt
For a ‘Windows Help’ version
>> doc sqrt
Exercise:
Verify that e^(i*x) = cos(x) + i*sin(x) (Euler’s equation) for a few values of x.
Tip: Use exp(x) for the e x
function
>> x = pi/3;
>> a = exp(i*x);
>> b = cos(x) + i*sin(x)
>> a - b
size() & length()
You can tell the difference between a row and a column
vector by:
Looking in the workspace
Displaying the variable in the command window
Using the size() function –
shows Try this
>> column = [1; 2; 3; 4]
[(no. of rows) (no. of cols)] >> row = [5 6 7 8]
>> size(column)
>> size(row)
To get a vector's length, use the length() function
Now try this
>> length(row)
>> length(column)
transpose()
The transpose operators turns a column vector into a row vector and vice
versa
a = [1 2 3 4]
transpose(a)
Can use dot-apostrophe as short-cut
a.‘
The apostrophe (without the dot) gives the Hermitian-transpose, i.e.
transposes and conjugates all complex numbers
Try this
>> mat1 = [1+j 2+3*j]
>> mat1’
>> mat1.’
For vectors of real numbers .' and ' give same result
Addition and Subtraction
Addition and subtraction are element-wise; sizes must match (unless one is
a scalar):
12 3 32 11 12 3 9
1 1 2
2 11 30 32
10 13 23
14 14 2 21
0 33
33
Try this
>> row = [1 2 3 4]
>> column = [4; 5; 6; 7]
>> c = row + column
Error! Incompatible sizes. Now try this
>> c = row + column’
>> c = row’ + column
Can sum up or multiply elements of vector
s=sum(row);
p=prod(row);
Addition and Subtraction (cont.)
If one operand is a scalar and the other a matrix, then addition/subtraction
will be done on each element.
Try this
>> our_matrix = [1 2;3 4]
>> result = our_matrix + 5
Element-Wise Functions
All the functions that work on scalars also work on
vectors
t = [1 2 3];
f = exp(t);
is the same as
f = [exp(1) exp(2) exp(3)];
If in doubt, check a function’s help file to see if it handles
vectors element-wise
Operators (* / ^) have two modes of operation
element-wise
standard
Operators: element-wise
To do element-wise operations, use the dot < . > BOTH dimensions must match (unless one
is scalar)!
4 1 1 1 1 2 3 1 2 3
2 2 2 .* 1 2 3 2 4 6
1 2 3 .* 2 ERROR
1 3 3 3 1 2 3 3 6 9
1 4 4 3 3.* 3 3 3 3
2 .* 2 4
3 1 3
3 1.* 3 1 3 1 Try this
>> a = [1 3 3]; b = [4;2;1];
>> a.*b
1 2 12 22 >> a./b
3 4 .^ 2 2 2
>> a.^b
3 4 All Errors!
>> a.*b’
Can be any dimension >> a./b’
>> a.^(b’)
All Valid
Operators: standard
Multiplication can be done in a standard way or element-wise
Standard multiplication (*) is either a dot-product or an outer-product
Remember from linear algebra: inner dimensions must MATCH! (for matrix multiplication AxB,
number of columns of A = number of rows of B)
Standard exponentiation (^) implicitly uses *
Can only be done on square matrices or scalars
Try this
>> a = [1 2; 3 4]
>> a^2
>> a*a
Same result. a^2 = a*a. Now try
>> a.^2
Left and right division (/ \) is same as multiplying by inverse
A = [1 2;3 4];
B = [5 6;7 8];
C = A/B;
Tip:The inv() function gives the inverse of a matrix
is same as
C = A*inv(B);
Exercise: Vector Operations
Find the inner product between [1 2 3] and [3 5 4]
>> a = [1 2 3]*[3 5 4]’
Multiply the same two vectors element-wise
>> b = [1 2 3].*[3 5 4]
Calculate the sin of each element of the resulting vector
>> c = sin(b)
Automatic Initialization
Initialize a vector of ones, zeros, or random numbers
o=ones(1,10)
row vector with 10 elements, all with the value 1
z=zeros(23,1)
column vector with 23 elements, all 0
r=rand(1,45)
row vector with 45 elements with random values between interval [0,1]
n=nan(1,69)
row vector of NaNs (useful for representing uninitialized variables)
id = eye(5,5)
identity vector of 5x5
The general function call is:
>> ones[M,N]
Where M = number of rows
N = number columns
Automatic Initialization
To initialize a linear vector of values use linspace()
a=linspace(X,Y,Z)
starts at X, ends at Y (inclusive), Z values
Can also use colon operator (:)
b=X:Y:Z
starts at X, increments by Y, and ends at Z
increment can be decimal or negative
c=X:Z
if increment isn’t specified, default is 1
To initialize logarithmically spaced values use logspace()
similar to linspace()
Try these
>> a = linspace(1,10,5)
>> b = 1:2:10
>> c = 1:10
>> d = logspace(1,10,5)
Exercise: Vector Functions
Make a vector that has 10,000 samples of
f(x) = e^{-x}*cos(x), for x between 0 and 10.
>> x = linspace(0,10,10000);
>> f = exp(-x).*cos(x);
Vector Indexing
Matlab indexing starts with 1, not 0
a(n) returns the nth element
13 5 9 10
a(1) a(2) a(3) a(4)
The index argument can be a vector. In this case, each element is looked up
individually, and returned as a vector of the same size as the index vector.
x = [12 13 5 8];
a = x(2:4); a = [13 5 8];
b = x(1:end-1); b= [12 13 5];
The colon ( : ) specifies the index interval.
x(2:4) results in an index vector [2 3 4]. A
vector containing elements of x
corresponding to the indices is returned
Matrix Indexing
Matrices can be indexed in two ways
using subscripts (row and column)
using linear indices (as if matrix is a vector)
Matrix indexing: subscripts or linear indices
b(1,1) 14 33 b(1,2) b(1) 14 33 b(3)
b(2,1)
9 8 b(2,2) b(2)
9 8 b(4)
Picking sub-matrices:Try this:
>> A = rand(5,5)
>> A(1,3)
>> A(11)
>> A(1:3,1:2)
>> A([1 5 3], [1 4])
Advanced Indexing 1
The index argument can be a matrix. In this case, each element is looked up
individually, and returned as a matrix of the same size as the index matrix.
a=[-1 10 3 -2];
b=a([1 2 4;3 4 2]); 1 10 2 Try it
b
3 2 10
To select rows or columns of a matrix, use the colon :
12 5
c
2 13
d=c(1,:); d=[12 5];
e=c(:,2); e=[5;13]; And these!
c(2,:)=[3 6]; replaces second row of c
Advanced Indexing 2
MATLAB contains functions to help you find desired values within a vector or
matrix
Try this:
To get the minimum value and its index >> vec = [1 5 3 9 7]
use min() >> [minVal, minInd] = min(vec)
>> [maxVal, maxInd] = max(vec)
To get the maximum value and its index:
use max()
To find any the indices of specific values or ranges
use find()
Try this
>> ind = find(vec == 9);
>> ind = find(vec > 2 & vec < 6);
find expressions can be very complex, more on this later
To convert between subscripts and indices, use ind2sub, and sub2ind. Look up
help to see how to use them.
Exercise: Vector Indexing
Evaluate a sine wave at 1,000 points between 0 and 2*pi.
What’s the value at
Index 55
Indices 100 through 110
Find the index of
the minimum value,
the maximum value, and
values between -0.001 and 0.001
>> x = linspace(0,2*pi,1000);
>> y=sin(x);
>> y(55)
>> y(100:110)
>> [minVal,minInd]=min(y)
>> [maxVal,maxInd]=max(y)
>> inds=find(y>-0.001 & y<0.001)
Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
Plotting Vectors
Example
x=linspace(0,4*pi,10);
y=sin(x);
Plot values against their index
plot(y);
Usually we want to plot y versus x
plot(x,y);
MATLAB makes visualizing data
fun and easy!
What does plot do?
plot generates dots at each (x,y) pair and then connects the dots with a line
To make plot of a function look smoother, evaluate at more points
Try this
>> x=linspace(0,4*pi,10);
>> more_x = linespace(0,4*pi,1000);
>> plot(x,sin(x));
>> plot(more_x, sin(more_x));
x and y vectors must be same size or else you’ll get an error
Try this
>> plot([1 2], [1 2 3])
Error!
1 1
10 x values: 0.8
0.6
1000 x values:
0.8
0.6
0.4 0.4
0.2 0.2
0 0
-0.2 -0.2
-0.4 -0.4
-0.6 -0.6
-0.8 -0.8
-1 -1
0 2 4 6 8 10 12 14 0 2 4 6 8 10 12 14
Plot Options
Can change the line color, marker style, and line style by
adding a string argument
plot(x,y,’k.-’); Try this
>> x = linspace(0,4*pi,1000)
>> plot(x,sin(x),’b*-’);
color line-style
marker
Can plot without connecting the dots by omitting line
style argument
plot(x,y,’.’)
Look at help plot or doc plot for a full list of
colors, markers, and line-styles
Other Useful plot Commands
Much more on this in Lecture 2, for now some simple
commands
To plot two lines on the same graph
hold on;
To plot on a new figure
figure;
plot(x,y);
Play with the figure GUI to learn more
add axis labels
add a title
add a grid
zoom in/zoom out
Exercise: Plotting
Plot f(x) = e^x*cos(x) on the interval x = [0 10]. Use a
red solid line with a suitable number of points to get a
good resolution.
>> x=0:0.01:10;
>> plot(x,exp(x).*cos(x),’r’);
LAB REPORT Question 1
The maximum angular acceleration of a Geneva wheel
containing “n” slots is
M (1 M 2 ) Sin
aG 2
(1 M 2 2 MCos ) 2
1
1 M2
Cos
1 M2
2 M
Where 4M 4M and Sin( )
n
aG
Determine 2
when n=4?
LAB REPORT Question 2
The displacement of the slider of the slider–crank
mechanism shown in Figure is given by
s aCos ( ) b 2 (aSin ( ) e) 2
Plot the displacement as a function of the angle (in
degrees) when a=1, b=1.5, e=0.3 and 0≤ ≤360, that is,
use plot ( , s).
LAB REPORT Question 3
Conway’s game of life – is a zero player game, which
showcases evolution given a certain set of rules
The game of life universe is a 2D grid of square cells where
each cell can either be alive or dead.
Each cell interacts with its 8 neighbors
At each time step:
Any live cell with fewer than two live neighbors dies
Any live cell with two or three live neighbors lives on
Any live cell with more than three neighbors dies
Any dead cell with exactly three live neighbors becomes alive
You can decide the initial pattern yourself. Simulate the game
of life for a grid of size 50, for at least 50 time steps.
For each time step plot all x and y values with some color.
LAB REPORT Question 3
Submit your lab report along with your m files, on the
LMS before lab starts.
Late submissions will not be entertained.
End of Lecture 1
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
Hope that wasn’t too much!!