Você está na página 1de 21

University

of Maryland

A Mechanical Engineers
Guide to Matlab
Lucas Myers


With minor edits by Johan Larsson

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 1

Table of Contents
Useful Background in Matlab ....................................................................................................................... 2
Matrix Algebra ......................................................................................................................................... 2
Element-Wise Multiplication vs. Matrix Multiplication ........................................................................... 4
Function Handles ..................................................................................................................................... 5
Differential Equations (MATH246) ............................................................................................................... 7
Introduction to Statistics (ENME392) ........................................................................................................ 14
Random Number Generation ................................................................................................................ 14
Data Statistics ........................................................................................................................................ 15
Probability Distributions ........................................................................................................................ 17
Glossary ..................................................................................................................................................... 19
Bibliography ............................................................................................................................................... 20

Useful Background in Matlab

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 2

Useful Background in Matlab


Before getting into the main part of this manual, there are a few syntax rules and concepts that
are important to know. These should have been previously covered in MATH206, but they are
re-covered here for your convenience.

Matrix Algebra
Many people do not know that Matlab is simply an abbreviation for Matrix Laboratory. Almost
everything that Matlab does has some basis in matrix algebra. For this reason it is useful to
know commands in Matlab that allow you to reference and manipulate matrices.
When entering a matrix into Matlab a space means that you have moved to the next term in a
row (a comma also does this) and a semicolon means that you have moved to the next row. For
instance, the matrix
1 2 3
4 5 6
7 8 9
Would be entered in Matlab as:


Figure 1

Note that to make the matrix easier to look at, enter was hit after each semicolon to go to the
next line. This does not affect how Matlab interprets the matrix and looks much cleaner. To
reference a specific number in a matrix, simply enter the name of the matrix followed by the
coordinates of the element desired:

Figure 2

This gives the value of the entry in the second row and the third column, in this case 6. To
reference an entire column or row of a matrix, replace one of the dimension arguments with a
colon:


Figure 3

This creates matrices that consist only of either the first column or the first row of A:

Useful Background in Matlab

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 3


Figure 4

Finally, to reference only certain portions of a row or a column, enter the range desired across
the colon:

Figure 5

Gives:


Figure 6


Example 1
Given the system of equations:
5! + 2! 7! = 8
9! + ! + 4! = 2
! + 3! + ! = 1
Solve for ! , ! , and ! .
Recall that this system can be represented as
=
Where

Useful Background in Matlab

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 4

5 2 7
= 9 1 4
1 3 1

!
= !
!

8
= 2
1

To solve for the vector using Matlab enter the coefficient matrix A and the vector and then
enter A\b:


Figure 7

This gives the value of vector and therefore the values of ! , ! , and ! :


Figure 8

Element-Wise Multiplication vs. Matrix Multiplication


When multiplying two arrays (matrices) in Matlab, there are two ways of doing so. Using an
operator (multiplication, division, etc.) normally by typing it in between two terms instructs
Matlab to use standard matrix multiplication techniques. This often is not the result that you
desire. More often, the intent is for corresponding elements of the arrays to act on each other.
To achieve this result, type a period before the operator. This will tell Matlab to perform what is
known as element-wise multiplication.

Example 2
You are given data points for the masses of a system and their corresponding heights and
instructed to find their potential energies.
M= [10 20 30 40 50]
H= [5 10 15 20 25]
You know that g=9.81 / ! and that = so you enter in Matlab:

Useful Background in Matlab

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 5


Figure 9

Which generates the error:



Figure 10

The error occurs because Matlab is trying to perform matrix multiplication between M and H,
which are both 1x5 matrices. Remember that matrices can only be multiplied if the second
dimension of the first matrix and the first dimension of the second matrix agree. This is what
Matlab is saying in the error inner dimensions must agree. Change the last entry in your code
to have Matlab perform element-wise multiplication:

Figure 11

Which generates the final answer:


Figure 12

The five entries in U are the potential energies of each mass in the system (multiplied by 10! ).
It should be noted that the exception to this rule are scalars. For scalars, .* and * do the exact
same thing, which is why it was not necessary to enter .* in between g and M in the example
above because g is a scalar.

Function Handles
Function handles are an incredibly powerful tool in Matlab. They allow users to define their
own functions and then reference them later. They also allow the use of nested functions which
will be of particular interest in the fluid mechanics section of the manual. The function handle
operator is simply an @ symbol followed by the variables in the function in parentheses. For
instance, @(x,y) would refer to a function of x and y. For simple functions you can enter the
function following the function handle operator, or for more complex functions, you can simply
enter the name of a function described in a different code. In the case of using a function
handle to call from another script, the @ symbol will not be followed by variables.

Useful Background in Matlab

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 6

Example 3
Find:
!

! sin (2)
!

And the value of the function inside the integral at x=1, 2, 3, 4, 5


This is obviously a very hard problem to do by hand and it is very unlikely that an integration
such as this one would be performed without a computer in the real world.
Use Matlab to perform the numerical integration:

Figure 13

Which gives:


Figure 14

It is critical to include period in front of any multiplication, division, or power that does not
involve a scalar in a function handle to make it element wise. This is because Matlab uses
vectors when integrating the function and so the function must be able to return a vector
result. The function handle has effectively turned fun into the function. It is then very easy to
find values of the function by typing fun(x) and replacing x with a value or by using feval to
evaluate multiple values at once. Here we use feval:

Figure 15

Which gives the answers in the elements of matrix A:


Figure 16

Note that the 1:5 in the second argument of feval tells Matlab to evaluate from 1 to 5
counting by 1. If you have irregular locations at which you desire to evaluate fun, you can enter
the exact values in a matrix in the second argument:

Figure 17

Useful Background in Matlab

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 7

Differential Equations (MATH246)


By far the most important function that you will need to know for differential equations in
Matlab is ode45, a built in numerical differential equation solver that is extremely powerful. It
is particularly useful for solving differential equations that would be either tedious or
impossible to solve by hand. To get a sense of how it works look at the vector field for the
!"
differential equation !" = 1 .

Figure 18 (Larsson)

The two red lines are trajectories calculated by ode45 using the different initial conditions.
ode45 uses the value of the derivative at each point to calculate the trajectory that the solution
would follow. The main condition is that ode45 needs an expression for the derivative in terms
of and (it can be any two variables but in this case it is and ).
The basic syntax for ode45 is:

[T,Y] = ode45(odefun,tspan,y0)
where odefun is the differential equation that you are solving, tspan is the start and endpoint
of where you want a solution, and y0 is the initial condition at your starting point. If your
differential equation is second order or higher, there will be more than one initial condition.
The output of ode45 is a vertical matrix listing a series of t coordinates and the corresponding y
coordinates in the adjacent column.
Where most students begin to have trouble is with the syntax that ode45 requires. tspan is
the simplest of the inputs so we will begin with that. tspan is simply a horizontal matrix where
the first entry is your starting point and your last entry is your ending point:
tspan= [0 10]

Differential Equations (MATH246)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 8

This would tell Matlab that you wanted a solution to the differential equation where 0<t<10.
Note that the designation of t being the independent variable is arbitrary and that the user can
choose any variable that suits them.
The syntax of y0 is similar to the syntax of tspan in that they are both entered in a horizontal
matrix. If your differential equation is first order, the use of brackets on either side of the
matrix is not necessary because there will be only one initial condition. However if your
differential equation is higher order, the matrix will have multiple entries corresponding to
multiple initial conditions:

y0= [0 0 1]
This would correspond to a third order differential equation because there are 3 initial
conditions.
The most frustrating part of ode45 for students is always the odefun because it requires them
to write a separate function that is often not intuitive. We will now examine how to write the
function of a differential equation for ode45.

Example 1
The height of fluid in a tank h(t) whose outlet flow is dependent on the pressure head (height of
fluid) inside the tank and whose inlet flow is a function of time may be modeled via the
equation

0 = !

Find the solution for 0 < t < 30 if the following values for the parameters are given
(Maneval 3).
= 10 + 4 sin

=2

! = 1

To solve, create an m-file reading:


Figure 19

When creating a function, the variable to the right of function and to the left of the equal
sign is your output. When this variable is defined later on in the function code, Matlab will
know that that is the desired output of the function. For functions written for ode45, the
output should be the expression for the derivative. The term to the left of the equal sign is the
name of the function. This is how you will call the function later when solving the differential

Differential Equations (MATH246)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 9

equation. Save it as the name you chose (in this case tankfill) and then create another m-file
reading:


Figure 20

Here tspan and h0 and odefun are defined and then entered into ode45. The arguments
could be entered directly into ode45, but defining them first is considered good coding
practice. odefun can be defined as either the name of your differential equation function
surrounded by apostrophes or preceded by the @ symbol. The 5th line will create a graph of the
solution using the plot function:


Figure 21

You can see that the result is not very smooth. To fix this you can tell Matlab to use a smaller
step size by changing the first line to:

Figure 22

This tells Matlab to go from 0 to 30 using a step size of 0.01 and gives a much better result.

Differential Equations (MATH246)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 10


Figure 23

Differential Equations (MATH246)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 11

Fluid Mechanics (ENME331)


The semester project for fluid mechanics is extremely Matlab intensive and requires a great
deal of work writing a program to perform complex simulations. The most important skill to
have will be the ability to solve second order coupled differential equations. A coupled
differential equation system is a system where two variables are related through a third
arbitrary variable through differential equations. An example of a coupled system solution
!"

!"

would be solving expressions for !" and !" for a plot of x vs. y.
ode45 is only designed to solve first order differential equations so in order to solve coupled
second-order differential equations, some manipulation is required. The secret lies in the fact
that ode45 can solve vectors consisting of multiple expressions at once.

Example 1
If
!!!
!! !

= 2 + 3

!!!
!! !

= 8

Find the plot for t from 0 to 1 if 0 = 0 = ! 0 = ! 0 = 1.


First we must find a vector whose derivative is the given system. In this case that vector is:

And therefore the derivative vector is:

The way Matlab sees it, it is not solving for x and y. It is solving for z using the first derivative of
z that was given. To draw parallels to the example done in the differential equations section,
is h and is dhdt only now they are both vectors. However, for this to truly be a first order
differential equation for Matlab to solve, must be expressed as a function of . Luckily this is
not difficult to do because all of the entries in can be expressed using entries in :
! = 2
!! = 8 1 + (3)
! = 4
Fluid Mechanics (ENME331)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 12

!! = 2 1 + 3(3)
We now have a system that can be solved in Matlab. First create the differential equation
function in an m-file:


Figure 24

The output of the function dzdt is entered as a vector with semicolons separating the rows. It
could equivalently be entered:


Figure 25

Note that the second variable that you define in parentheses after the name of the function
must match the variable name used to represent and in the differential equation. For
example, if the function instead began:
dzdt=coupled_diff(t,g)
then all of the z terms would have to be replaced by g (i.e. z(2) would become g(2)).
Solving using ode45 in a separate m-file:


Figure 26

Gives:

Fluid Mechanics (ENME331)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 13


Figure 27

To make a code cleaner and have less files to save, an option is to put the differential equation
in the same script as your solver by creating two separate functions in the same script. The first
line of your solver will now be function name_of_script and the last line of the solver will
be end. Under the solver insert the differential equation code under it and similarly specify the
end of that function with end:


Figure 28

Doing this will allow quicker editing of the code and will prevent problems with different
Matlab paths from arising. The technique covered in this example can be simplified to solve
normal second order differential equations or first order coupled differential equations.



Fluid Mechanics (ENME331)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 14

Introduction to Statistics (ENME392)


Random Number Generation
In statistics, the ability to use Matlab to generate random numbers will be incredibly
useful. The four main function that can be used to do this are rand(), randn(), randi(),
and random(). The problem being solved will dictate which choice is the best to use.
rand(m,n) will generate random numbers evenly distributed over (0,1). The first two
input arguments are the dimensions of the matrix that will be generated. Each entry of the
generated matrix will have a different random number between 0 and 1. If you require
numbers distributed over a longer interval, you can multiply the function by a scalar. For
instance, to obtain a 3 x 2 matrix with numbers distributed from 0 to 10, type 10*rand(3,2).
To generate negative random numbers, you can subtract a constant (i.e 10*rand(3,2)-5
would be a uniform distribution of numbers from -5 to 5). This function is useful for probability
problems because probabilities are normally expressed as decimals between one and zero.

Alternatively, you could use randi([min, max],m,n), which allows you to specify
both the interval and the size of the matrix generated in the input arguments. To create a
uniform distribution in a 3 x 2 matrix from -5 to 5 here you would simply enter randi([-5,
5],3,2).

Distribution functions will make up a substantial part of the course, the most important
of which will be the normal distribution. To generate normally distributed random numbers,
use the function randn(m,n). It generates random numbers that are normally distributed
around zero by default, but there is no easy way to adjust the parameters of the distribution
(the mean and variance). In order to accommodate the needs of a problem will require using
algebraic tricks similar to those shown for rand().

Finally, the most powerful of the random number generating tools built into Matlab is
random(name,A,B,C,m,n). This can be used to create random numbers following just about
any probability distribution imaginable including normal, binomial, geometric, hypergeometric,
chi squared, Poisson, and Weibull, all of which will be covered during the course. To use
random(), enter the name of the distribution desired and then enter the corresponding
parameters of the distribution followed by the size of the matrix to be generated. The name of
the distribution must be surrounded by apostrophes. Shown below is a table of distributions
that random() supports and the order that the parameters of the distribution should follow. If
a distribution does not have a third or second parameter, the argument after the last
parameter becomes the first dimension of the matrix to be generated.

Introduction to Statistics (ENME392)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 15



Distribution
Binomial

Name
bino

Chi-Square

chi2

Exponential
F

exp
F

Geometric
Hypergeometric

geo
hyge

Negative
Binomial
Normal

nbin

Poisson
t

poiss
t

norm

Table 1 (MathWorks)

A
n: number of
trials
v: degrees of
freedom
u: mean
v1: numerator
degrees of
freedom
p: probability
m: size of
population
r: number of
successes
u: mean
: mean
v: degrees of
freedom

B
P: probability of
success


v2: denominator
degrees of
freedom

k: number of
items with
desired
characteristic
p: probability of
success in trial
: standard
deviation


n: number of
samples drawn



Data Statistics
When given a set of data, it is often useful to characterize the data with certain quantities,
particularly if your data resembles a normal distribution. The main functions that you will need
to know are mean() and std().
mean(X), as you may have guessed, will find the average of a given set of data X. Given a
matrix of data for the input, it will output the average value for each of the columns in the
matrix. For this reason, to find the average of a single set of data, the input matrix must be a
column vector (as opposed to a row vector, which is horizontal).
std(X) is the Matlab function for finding the standard deviation of a given set of data X.
Similar the mean() function, it will find the standard deviation for each of the columns of the
input matrix and so the input must be a column vector or can be used to find the standard
deviation of many data sets at once. This can be useful when performing analysis of variance
for multiple sets of data.

Introduction to Statistics (ENME392)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 16

Example 1
Generate a random set of numbers of 100 numbers following a normal distribution with a mean
of 0 and a standard deviation of 2 and then find the average and standard deviation of your
generated data. How close to the given values and calculated values match?
First use the random() function with a normal distribution to generate a 100x1 matrix of
numbers with an average of 5 and a standard deviation of 2. Then use mean() and std() to
compute the average and standard deviation of the data generated.


Figure 29

This code generates the result:


Figure 30

Note that the average of the data generated and the standard deviation do not correspond
exactly to the values given to the generator. This is due to the random variation of the
numbers. You will find that you get a slightly different result every time this code is run due to
random variation. To get a more reliable answer, increase the sample to 100,000:


Figure 31

The results will now be consistently very close to the given values for the mean and standard
deviation:

Introduction to Statistics (ENME392)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 17


Figure 32

Probability Distributions
In addition to being able to generate random numbers that follow probability distributions, it
will also be useful to know the values of the normal distribution. The three functions important
to analyzing the normal distribution are normpdf(), normcdf(), and norminv(). The
suffixes pdf, -cdf, and inv are short for probability distribution function, cumulative
distribution function, and inverse cumulative.
normpdf(x,mu,sigma) gives the value of a normal distribution function described by the
given mean and standard deviation at x.
normcdf(x,mu,sigma) gives the cumulative probability from the left of a normal distribution
function to x. Mathematically, this means that it is integrating the normal distribution function
from = to = 0. In other words it calculates the total probability that something will be
found at x or at any value lower than x on a normal distribution. This can be used to calculate
probabilities across ranges of x (see example 2). This function is a huge timesaver because it
replaces the tedious process of calculating z-values for a given x values and then looking up the
probability in a table.
norminv(p,mu,sigma) gives a value of x that corresponds to a cumulative p-value for a
normal distribution described by a given mean and standard deviation. Note that p must be less
than 1 because it is a probability. This function will make calculating confidence intervals
incredibly quick and easy.
The values of x or p in the functions above can also be vectors which allows for quick calculation
of many different values. In the case of vector a vector input, the output will be a vector of the
same size as the input. These three features are available for all distributions and can be
accessed by adding the suffix pdf, -cdf, or inv to the name of the desired function from Table
1. For instance the entry for the cumulative distribution function of chi-squared would be
chi2cdf().

Example 2

Introduction to Statistics (ENME392)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 18

Structural 2x4s made at Lucass Lumber are known to have an average length of 72 in with a
standard deviation of 1 in. Bob the Builder goes and buys a 2x4 from Lucass Lumber for a porch
he is building. How likely is it that Bob will get a 2x4 that is in between 71 in and 73 in (this is
question2 below)? What lengths can Lucass Lumber be 95% sure that Bobs 2x4 was in
between (this is question3 below)?
Solve using the functions from above:


Figure 33

To find the probability in between 71 in and 73 in, we calculate the difference between the
cumulative probability to 73 and 71 using normcdf(). To answer the third question, we use
norminv() to calculate the value corresponding to both 2.5% cumulative probability and
97.5% cumulative probability (95% difference) at the same time by entering the two values in a
matrix. The answer to question 3 appears as a vector of the same size as the input vector:


Figure 34

Introduction to Statistics (ENME392)

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 19

Glossary
Argument- Argument refers to the input of a function in Matlab. Depending on the function,
there can be one or more arguments required. Arguments are entered in parentheses following
the function name in a set order separated by commas.
Array- An array in Matlab is another term for matrix. Most literature will refer to matrices in
Matlab as arrays so it is important to know that they are the same.
Element- An element refers to a specific, single entry in an array.
Confidence Interval- A confidence interval is the range of values that contain a given amount of
probability in a probability distribution. For instance, a 95% confidence interval would be the
values containing the middle 95% of the normal distribution (This would mean leaving 2.5% on
both the high and low end).
Order-The order of a differential equation refers the level of the highest derivative. A first order
differential equation will have up to first derivatives. A second order equation will have up to
second derivatives and so on.

Glossary

12/13/2015

A M e c h a n i c a l E n g i n e e r s G u i d e t o M a t l a b | 20

Bibliography
Alterovitz, Gil. "Massachusetts Institute of Technology Integrates Cancer Research in the Lab
and Classroom." Mathworks.com. MathWorks, 1 July 2015. Web. 3 Nov. 2015.
Craig, James. "More than 1,000 Georgia Tech Engineering Students Learn Computer Science
Concepts Each Semester with MATLAB."MathWorks.com. MathWorks, 1 June 2006. Web. 3
Nov. 2015.
Duncan, James. Personal Interview. 1 Dec. 2015
Hodge, B.K., and W.G. Steele. "A Survey of Computational Paradigms in Undergraduate
Mechanical Engineering Education." Journal of Engineering Education 91.4 (2013): 415-17.
Wiley Online Library. Web. 25 Oct. 2015.
Hogan, Jacob. Matlab Education at the University of Maryland. Survey. Forthcoming.
Lanigan, Mary. How to Create Effective Training Manuals. Tinley Park: Third House, 2010. Print.
Larsson, Johan. Personal Interview. 20 Nov 2015
Li, Xiaosong. Proceedings of the 6th conference on Information technology education. New York:
ACM. 20 Oct. 2005. Print.
Kiger, Kenneth. Department of Mechanical Engineering. University of Maryland, June 2011.
Web. 13 Dec. 2015
Magrab, Edward B., Shapour Azarm, Balakumar Balachandran, James Duncan, Keith Harold, and
Gregory Walsh. An Engineer's Guide to MATLAB. 3rd ed. Upper Saddle River: Prentice Hall,
2011. Print.
Maneval, Jim. "Using ODE45." www.facstaff.bucknell.edu/maneval/. Bucknell University, 1 Oct.
2010. Web. 12 Dec. 2015.
Manning, Sean. Personal Interview. 25 Oct. 2015
Pines, Darryll. Senate Committee on Programs, Curricula, and Courses. 6 Apr. 2012, 0118 Main
Administration Building. College Park: Office of the Senior Vice President and Provost, 13 Jul.
2012. Print.
Senan, Nur Adila Faruk. "A Brief Introduction to Using Ode45 in MATLAB."
www.eng.auburn.edu. Auburn University, 9 Jan. 2012. Web. 12 Dec. 2015.
Wyss-Gallifent, Justin. Personal Interview. 24 Oct. 2015

Bibliography

12/13/2015

Você também pode gostar