Nothing Special   »   [go: up one dir, main page]

Matlab Tutorial - Short

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

EML3017C

Mechanical Systems I

Mechanical Systems I
Background: The tutorials below provide a simple introduction to Matlab and detail on the Lab Exercise.

1. Vectors
A basic introduction on how to define and manipulate vectors in Matlab.

2. Matrices
Demonstrating how to create matrices and how to access parts of a matrix.

3. Vector operations
How to bring together elements of the first two tutorials. The real power of Matlab is that the basic
linear algebra operations can be carried out with similar notation and few programming steps.

4. Loops
Introduction to the basic loop construct used in Matlab.

5. Plots
A very basic overview of the plotting commands is given.

6. Executable Files
Defining files of commands that Matlab can execute as if they were entered at the command prompt.

7. Subroutines
Creating executable file in which generic arguments are passed back and forth.

8. If statements
The "if" statement allows for conditional execution of certain parts of a code.

Introduction to Vectors in Matlab


This is the basic introduction to Matlab. Creation of vectors is included with a few basic operations. Topics
include the following:
1

1.
2.
3.
4.

Defining a vector
Accessing elements within a vector
Basic operations on vectors
Modifying vector elements

Defining a Vector
Matlab is a software package that makes it easier for you to enter matrices and vectors, and manipulate them.
The interface follows a language that is designed to look a lot like the notation use in linear algebra. In the
following tutorial, we will discuss some of the basics of working with vectors.
If you are running windows or Mac OSX, you can start Matlab by choosing it from the menu. To start Matlab
on a UNIX system, open up a UNIX shell and type the command to start the software: Matlab. This will start up
the software, and it will wait for you to enter your commands. In the text that follows, any line that starts with
two greater than signs (>>) is used to denote the Matlab command line. This is where you enter your commands.
Almost all of Matlab's basic commands revolve around the use of vectors. A vector is defined by placing a
sequence of numbers within square braces:
>> v = [3 1]
v =
3

This creates a row vector which has the label "v". The first entry in the vector is a 3 and the second entry is a 1.
Note that Matlab printed out a copy of the vector after you hit the enter key. If you do not want to print out the
result put a semi-colon at the end of the line:
>> v = [3 1];
>>

If you want to view the vector just type its label:


>> v
v =
3

You can define a vector of any size in this manner:


>> v = [3 1 7 -21 5 6]
v =
3

-21

Notice, though, that this always creates a row vector. If you want to create a column vector you need to take the
transpose of a row vector. The transpose is defined using an apostrophe ():
2

>> v = [3 1 7 -21 5 6]'


v =
3
1
7
-21
5
6

A common task is to create a large vector with numbers that fit a repetitive pattern. Matlab can define a set of
numbers with a common increment using colons. For example, to define a vector whose first entry is 1, the
second entry is 2, the third is 3, and up to 8 you enter the following:
>> v = = [1:8]
v =
1

If you wish to use an increment other than one that you have to define the start number, the value of the
increment, and the last number. For example, to define a vector that starts with 2 and ends in 4 with steps of .25
you enter the following:
>> v = [2:.25:4]
v =
Columns 1 through 7
2.0000

2.2500

2.5000

2.7500

3.0000

3.2500

3.5000

Columns 8 through 9
3.7500

4.0000

Accessing elements within a vector


You can view individual entries in this vector. For example to view the first entry just type in the following:
>> v(1)
ans =
2

This command prints out entry 1 in the vector. Also notice that a new variable called ans has been created. Any
time you perform an action that does not include an assignment Matlab will put the label ans on the result.

To simplify the creation of large vectors, you can define a vector by specifying the first entry, an increment, and
the last entry. Matlab will automatically figure out how many entries you need and their values. For example, to
create a vector whose entries are 0, 2, 4, 6, and 8, you can type in the following line:
3

>> 0:2:8
ans =
0

Matlab also keeps track of the last result. In the previous example, a variable "ans" is created. To look at the
transpose of the previous result, enter the following:
>> ans'
ans =
0
2
4
6
8

To be able to keep track of the vectors you create, you can give them names. For example, a row vector v can be
created:
>> v = [0:2:8]
v =
0

>> v
v =

>> v;
>> v'
ans =
0
2
4
6
8

Note that in the previous example, if you end the line with a semi-colon, the result is not displayed. This will
come in handy later when you want to use Matlab to work with very large systems of equations.
Matlab will allow you to look at specific parts of the vector. If you want to only look at the first three entries in
a vector you can use the same notation you used to create the vector:
>> v(1:3)
ans =

>> v(1:2:4)
ans =
0

>> v(1:2:4)'
ans =
0
4

Basic operations on vectors


Once you master the notation you are free to perform other operations:
>> v(1:3)-v(2:4)
ans =
-2

-2

-2

For the most part Matlab follows the standard notation used in linear algebra. We will
see later that there are some extensions to make some operations easier. For now, though,
both addition subtraction are defined in the standard way. For example, to define a new
vector with the numbers from 0 to -4 in steps of -1 we do the following:
>> u = [0:-1:4]
u = [0:-1:-4]
u =
0

-1

-2

-3

-4

We can now add u and v together in the standard way:


>> u+v
ans =
0

Additionally, scalar multiplication is defined in the standard way. Also note that scalar division is defined in a
way that is consistent with scalar multiplication:
>> -2*u
ans =
0

>> v/3

ans =
0
0.6667
1.3333
2.0000
2.6667
With these definitions linear combinations of vectors can be easily defined and the basic
operations combined:
>> -2*u+v/3
ans =
0

2.6667

5.3333

8.0000

10.6667

You will need to be careful. These operations can only be carried out when the dimensions of the vectors allow
it. You will likely get used to seeing the following error message which follows from adding two vectors whose
dimensions are different:
>> u+v'
??? Error using ==> plus
Matrix dimensions must agree.

Adding or Removing elements from a vector


Given the following vector,:
>> v = [5 6 7]
v =
5

You can add one or more elements to a vector:

>> v = [v:4]
v =
5

>> v = [v:[7 9]]


v =
5

Of course, removing elements from the vector is just as easy. Lets remove the second element in the vector.
>> v(2) = []

v =
5

Introduction to Matrices in Matlab


A basic introduction to defining and manipulating matrices is given here. It is assumed that you know the basics
on how to define and manipulate vectors using Matlab.
1. Defining Matrices
2. Matrix Functions

Defining Matrices
Defining a matrix is similar to defining a vector. To define a matrix, you can treat it like a column of row
vectors (note that the spaces are required!):
>> A = [ 1 2 3; 3 4 5; 6 7 8]
A =
1
3
6

2
4
7

3
5
8

You can also treat it like a row of column vectors:


>> B = [ [1 2 3]' [2 4 7]' [3 5 8]']
B =
1
2
3

2
4
7

3
5
8

(Again, it is important to include the spaces.)


If you have been putting in variables through this and the tutorial on vectors, then you probably have a lot of
variables defined. If you lose track of what variables you have defined, the whos command will let you know all
of the variables you have in your work space.
>> whos
Name
A
B
v

Size
3x3
3x3
1x5

Bytes
72
72
40

Class
double array
double array
double array

Grand total is 23 elements using 184 bytes

We assume that you are doing this tutorial after completing the previous tutorial. The vector v was defined in
the previous tutorial.
As mentioned before, the notation used by Matlab is the standard linear algebra notation you should have seen
before. Matrix-vector multiplication can be easily done. You have to be careful, though, your matrices and
vectors have to have the right size!
>> v = [0:2:8]
v =
0

>> A*v(1:3)
??? Error using ==> *
Inner matrix dimensions must agree.
>> A*v(1:3)'
ans =
16
28
46

Get used to seeing that particular error message! Once you start throwing matrices and vectors around, it is easy
to forget the sizes of the things you have created.
You can work with different parts of a matrix, just as you can with vectors. Again, you have to be careful to
make sure that the operation is legal.
>> A(1:2,3:4)
??? Index exceeds matrix dimensions.
>> A(1:2,2:3)
ans =
2
4

3
5

>> A(1:2,2:3)'
ans =
2
3

4
5

Matrix Functions

Once you are able to create and manipulate a matrix, you can perform many standard operations on it. For
example, you can find the inverse of a matrix. You must be careful, however, since the operations are numerical
manipulations done on digital computers. In the example, the matrix A is not a full matrix, but Matlab's inverse
routine will still return a matrix.
>> inv(A)
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 4.565062e-18

ans =
1.0e+15 *
-2.7022
5.4043
-2.7022

4.5036
-9.0072
4.5036

-1.8014
3.6029
-1.8014

By the way, Matlab is case sensitive. This is another potential source of problems when you start building
complicated algorithms.
>> inv(a)
??? Undefined function or variable a.

Matlab is great for doing all types of matrix manipulations; consider the transpose,
>> transpose(A)
ans =
1
2
3

3
4
5

6
7
8

Or, as before with the vector, consider using the (single quote) for the transpose.
>> A'
ans =
1
2
3

3
4
5

6
7
8

Finally, sometimes you would like to clear all of your data and start over. You do this with the "clear" command.
Be careful though, it does not ask you for a second opinion and its results are final.
9

>> clear
>> whos

Vector Functions
Matlab makes it easy to create vectors and matrices. The real power of Matlab is the ease in which you can
manipulate your vectors and matrices. Here we assume that you know the basics of defining and manipulating
vectors and matrices. In particular we assume that you know how to create vectors and matrices and know how
to index into them. For more information on those topics see our tutorial on either vectors or matrices.
In this tutorial we will first demonstrate simple manipulations such as addition, subtraction, and multiplication.
Following this basic "element-wise" operations are discussed. Once these operations are shown, they are put
together to demonstrate how relatively complex operations can be defined with little effort.
First, we will look at simple addition and subtraction of vectors. The notation is the same as found in most
linear algebra texts. We will define two vectors and add and subtract them:
>> v = [1 2 3]'
v =
1
2
3
>> b = [2 4 6]'
b =
2
4
6
>> v+b
ans =
3
6
9
>> v-b
ans =
-1
-2
-3

Multiplication of vectors and matrices must follow strict rules. Actually, so must addition. In the example above,
the vectors are both column vectors with three entries. You cannot add a row vector to a column vector.
10

Multiplication, though, can be a bit trickier. The number of columns of the thing on the left must be equal to the
number of rows of the thing on the right of the multiplication symbol:
>> v*b
??? Error using ==> *
Inner matrix dimensions must agree.
>> v*b'
ans =
2
4
6

4
8
12

6
12
18

>> v'*b
ans =
28

There are many times when we want to do an operation to every entry in a vector or matrix. Matlab will allow
you to do this with "element-wise" operations. For example, suppose you want to multiply each entry in vector
v with its corresponding entry in vector b. In other words, suppose you want to find v(1)*b(1), v(2)*b(2), and
v(3)*b(3). It would be nice to use the "*" symbol since you are doing some sort of multiplication, but since it
already has a definition, we have to come up with something else. The programmers who came up with Matlab
decided to use the symbols ".*" to do this. In fact, you can put a period in front of any math symbol to tell
Matlab that you want the operation to take place on each entry of the vector.
>> v.*b
ans =
2
8
18
>> v./b
ans =
0.5000
0.5000
0.5000

Since we have opened the door to non-linear operations, why not go all the way? If you pass a vector to a
predefined math function, it will return a vector of the same size, and each entry is found by performing the
specified operation on the corresponding entry of the original vector:
>> sin(v)
ans =
0.8415

11

0.9093
0.1411
>> log(v)
ans =
0
0.6931
1.0986

It is easy to find the largest element and average of a vectors elements:


>> v = [2 5 3 9 7 1];
>> max(v)
ans =
9
>> mean(v)
ans =
4.5000

The ability to work with these vector functions is one of the advantages of Matlab. Now complex operations can
be defined that can be done quickly and easily. In the following example a very large vector is defined and can
be easily manipulated. (Notice that the second command has a ";" at the end of the line. This tells Matlab that it
should not print out the result.)
>> x = [0:0.1:2*pi]
x =
Columns 1 through 7
0

0.1000

0.2000

0.3000

0.4000

0.5000

0.6000

0.9000

1.0000

1.1000

1.2000

1.3000

5.1000

5.2000

5.3000

5.4000

5.5000

5.8000

5.9000

6.0000

6.1000

6.2000

Columns 8 through 14
0.7000

0.8000

[stuff deleted]
Columns 50 through 56
4.9000

5.0000

Columns 57 through 63
5.6000

5.7000

>> y = sin(x).*x./(1+cos(x));

12

Through this simple manipulation of vectors, Matlab will also let you graph the results. The following example
also demonstrates one of the most useful commands in Matlab, the "help" command.
>> plot(x,y)

150

100

50

-50

-100

-150

Consider replacing the line plot with one consisting of red xs,
>> plot(x,y,'rx')
150

100

50

-50

-100

-150

>> help plot


PLOT
Linear plot.
PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix,
then the vector is plotted versus the rows or columns of the matrix,
whichever line up. If X is a scalar and Y is a vector, length(Y)
disconnected points are plotted.

13

PLOT(Y) plots the columns of Y versus their index.


If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)).
In all other uses of PLOT, the imaginary part is ignored.
Various line types, plot symbols and colors may be obtained with
PLOT(X,Y,S) where S is a character string made from one element
from any or all the following 3 columns:
b
g
r
c
m
y
k

blue
green
red
cyan
magenta
yellow
black

.
o
x
+
*
s
d
v
^
<
>
p
h

point
circle
x-mark
plus
star
square
diamond
triangle (down)
triangle (up)
triangle (left)
triangle (right)
pentagram
hexagram

:
-.
--

solid
dotted
dashdot
dashed

For example, PLOT(X,Y,'c+:') plots a cyan dotted line with a plus


at each data point; PLOT(X,Y,'bd') plots blue diamond at each data
point but does not draw any line.
[stuff deleted]

You can improve your plots by including grid lines, titles, x and y labels, and much more. For example,
consider,
>> plot(x,y,'y',x,y,'go'),title('My First Plot'),xlabel('x'),ylabel('y')
My First Plot

150

100

50

-50

-100

-150

The compact notation will let you tell the computer to do lots of calculations using few commands. For example,
suppose you want to calculate the divided differences for a given equation. Once you have the grid points and
the values of the function at those grid points, building a divided difference table is simple:
14

>>
>>
>>
>>
>>

coef = zeros(1,63);
coef(1) = y(1);
y = (y(2:63)-y(1:62))./(x(2:63)-x(1:62));
coef(2) = y(1);
y(1)

ans =
0.0500
>> y = (y(2:62)-y(1:61))./(x(3:63)-x(1:61));
>> coef(3) = y(1);

From this algorithm you can find the Lagrange polynomial that interpolates the points you defined above
(vector x). Of course, with so many points, this might get a bit tedious. Fortunately, Matlab has an easy way of
letting the computer do the repetitive things, which is examined in the next tutorial.

Loops
In this tutorial we will demonstrate how the for and the while loop are used. First, the for loop is discussed with
examples for row operations on matrices and for Euler's Method to approximate an ODE. Following the for
loop, a demonstration of the while loop is given.
We will assume that you know how to create vectors and matrices and know how to index into them. For more
information on those topics see one of our tutorials on vectors, matrices, or vector operations.
1. For Loops
2. While Loops

For Loops
The for loop allows us to repeat certain commands. If you want to repeat some action in a predetermined way,
you can use the for loop. All of the loop structures in Matlab are started with a keyword such as "for", or
"while" and they all end with the word "end". Another deep thought, eh.
The for loop is written around some set of statements, and you must tell Matlab where to start and where to end.
Basically, you give a vector in the "for" statement, and Matlab will loop through for each value in the vector:
For example, a simple loop will go around 4 times each time changing a loop variable, j:
>> for j=1:4,
j
end

j =
1

15

j =
2

j =
3

j =
4

When Matlab reads the "for" statement it constructs a vector, [1:4], and j will take on each value within the
vector in order. Once Matlab reads the "end" statement, it will execute and repeat the loop. For each loop, the
for statement will update the value of j and repeat the statements within the loop. In this example it will print
out the value of j each time.
For another example, we define a vector and later change the entries. Here we step though and change each
individual entry:
>> v = [1:3:10]
v =
1

10

>> for j=1:4,


v(j) = j;
end
>> v
v =
1

Note, that this is a simple example and is a nice demonstration to show you how a for loop works. However,
DO NOT DO THIS IN PRACTICE!!!! Matlab is an interpreted language and looping through a vector like
this is the slowest possible way to change a vector. The notation used in the first statement is much faster than
the loop.
A better example, is one in which we want to perform operations on the rows of a matrix. If you want to start at
the second row of a matrix and subtract the previous row of the matrix and then repeat this operation on the
following rows, a for loop can do this in short order:
>> A = [ [1 2 3]' [3 2 1]' [2 1 3]']
A =
1
2

3
2

2
1

16

>> B = A;
>> for j=2:3,
A(j,:) = A(j,:) - A(j-1,:)
end
A =
1
1
3

3
-1
1

2
-1
3

1
1
2

3
-1
2

2
-1
4

A =

For a more realistic example, since we can now use loops and perform row operations on a matrix, Gaussian
Elimination can be performed using only two loops and one statement:
>> for j=2:3,
for i=j:3,
B(i,:) = B(i,:) - B(j-1,:)*B(i,j-1)/B(j-1,j-1)
end
end
B =
1
0
3

3
-4
1

2
-3
3

1
0
0

3
-4
-8

2
-3
-3

1
0
0

3
-4
0

2
-3
3

B =

B =

Another example where loops come in handy is the approximation of differential equations. The following
example approximates the D.E. y'=x^2-y^2, y(0)=1, using Euler's Method. First, the step size, h, is defined.
Once done, the grid points are found, and an approximation is found. The approximation is simply a vector, y,
in which the entry y(j) is the approximation at x(j).

17

>>
>>
>>
>>
>>

h = 0.1;
x = [0:h:2];
y = 0*x;
y(1) = 1;
size(x)

ans =
1

21

>> for i=2:21,


y(i) = y(i-1) + h*(x(i-1)^2 - y(i-1)^2);
end
>> plot(x,y,'go',x,y)
2

1.8

1.6

1.4

1.2

0.8

0.2

0.4

0.6

0.8

1.2

1.4

1.6

1.8

While Loops
If you don't like the for loop, you can also use a while loop. The while loop repeats a sequence of commands as
long as some condition is met. This can make for a more efficient algorithm. In the previous example the
number of time steps to make may be much larger than 20. In such a case the for loop can use up a lot of
memory just creating the vector used for the index. A better way of implementing the algorithm is to repeat the
same operations but only as long as the number of steps taken is below some threshold. In this example the D.E.
y'=x-|y|, y(0)=1, is approximated using Euler's Method:
>>
>>
>>
>>
>>
>>

h = 0.001;
x = [0:h:2];
y = 0*x;
y(1) = 1;
i = 1;
size(x)

ans =
1

2001

>> max(size(x))

18

ans =
2001
>> while(i<max(size(x)))
y(i+1) = y(i) + h*(x(i)-abs(y(i)));
i = i + 1;
end
>> plot(x,y,'r-.')
1.4
1.3
1.2
1.1
1
0.9
0.8
0.7

0.2

0.4

0.6

0.8

1.2

1.4

1.6

1.8

Plotting
In this tutorial we will assume that you know how to create vectors and matrices, know how to index into them,
and know about loops. For more information on those topics see one of our tutorials on vectors, matrices, vector
operations, or loops.
In this tutorial we will see how easily you can use Matlab to create great plots. Consider a particle moving along
the x-axis, its position at each time t given by the function

x t t 3 12t 2 36t 27
We can obtain the velocity by differentiating the position function:

v t 3t 2 24t 36
Likewise, the acceleration can be found by differentiating the velocity function:

a t 6t 24 .

19

Well plot the position, velocity, and acceleration from time t = 1 to t = 9 seconds. In the following program you
will see words following the symbol %. In Matlab the % symbol is a comment indicator; anything after the %
symbol is ignored by the computer and is simply used by the programs author to explain in words what the
program code is doing.

>> num = (9-1)/0.1;


>> x = zeros(1,num); % vector for position initially filled with zeros
>> v = zeros(1,num); % vector for velocity
>> a = zeros(1,num); % vector for acceleration
>> i = 0; % counter for stepping through vectors
>> for t = 1:0.1:9,
i = i + 1;
x(i) = t^3-12*t^2+36*t-27;
v(i) = 3*t^2 - 24*t + 36;
a(i) = 6*t - 24;
end
>> i = 1:0.1:9;
>> subplot(3,1,1),plot(i,x,'g-'),title('Pos'),ylabel('in'),grid on
>> subplot(3,1,2),plot(i,v,'b--'),title('Vel'),ylabel('in/sec'),grid on
>> subplot(3,1,3),...
plot(i,a,'r-.'),title('Acc'),ylabel('in/sec^2'),xlabel('sec'),grid on

Pos

100
in

50
0
-50

in/sec

100

50
0
-50

5
Acc

40
in/sec 2

5
Vel

20
0
-20

5
sec

20

You might also like