Top Banner
Lecture Aims Built-in functions Graphics Help Programming with MATLAB Objectives Example problem M-Files Script files Function files Example N.M. 2.1 Lecture N.M. 2 Introduction to MATLAB Part 2 CHE 4163 Transport Phenomena and Numerical Methods Ravi Jagadeeshan Department of Chemical Engineering Monash University
25

MATLAB2 Beamer

Jul 16, 2016

Download

Documents

venkiee

Software
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.1

Lecture N.M. 2Introduction to MATLABPart 2

CHE 4163 Transport Phenomena and Numerical Methods

Ravi JagadeeshanDepartment of Chemical Engineering

Monash University

Page 2: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.2

Aims of todays lecture and examples

1 Learning about MATLAB’s built-in functions

2 Quick start guide to Graphics with MATLAB

3 Basics of developing M-files in MATLAB

4 Distinguishing between script files and function files

5 Example problems on script files and function files

Page 3: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.3

Table of Contents

1 Built-in functions

2 Graphics

3 Help

4 Programming with MATLABObjectivesExample problem

5 M-FilesScript filesFunction filesExample

Page 4: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.4

Built-in functions

• MATLAB and its Toolboxes have a rich collection of built-infunctions

• You can use online help to find out more about them

• For example, if you want to learn about the logfunction, type in:>> help log

• For a list of all the elementary functions, type>> help elfun

• One of the important properties of MATLAB’ s built-infunctions is that they will operate directly on vector andmatrix quantities

• For example, try>> log (A)

Page 5: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.5

Built-in functions

• The natural logarithm function is applied in array style,element by element, to the matrix A

• Most functions, such as sqrt, abs, sin, acos, tanh, andexp, operate in array fashion

• Certain functions, such as exponential and square root,have matrix definitions also

• MATLAB will evaluate the matrix version when the letter mis appended to the function name

• Try>> sqrtm(A)

• A common use of functions is to evaluate a formula for aseries of arguments

Page 6: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.6

Built-in functions

• Consider the function,

v(t) =gmc

(1− e−(c/m)t)

where v is velocity (m/s), g is the acceleration due togravity (9.81 m/s2), m is mass (kg), c is the drag coefficient(kg/m), and t is time (s)

• Create a column vector t that contains values from 0 to200 in steps of 2>> t = [0:2:200]’;

• Check the number of items in the t array with the lengthfunction>> length(t)

• Assign values to the parameters:>> g = 9.81; m = 8.1; c = 0.25;

Page 7: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.7

Built-in functions

• MATLAB allows you to evaluate a formula such asv = f(t), where the formula is computed for each valueof the t array, and the result is assigned to acorresponding position in the v array:>> v = (g*m/c)*(1 - exp(-(c/m)*t));

Graphics

• MATLAB allows graphs to be created quickly andconveniently

• For example, to create a graph of the t and v arrays fromthe data above, enter>> plot (t, v)

• The graph appears in the graphics window and can beprinted or transferred via the clipboard to other programs

Page 8: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.8

Graphics

• You can customize the graph a bit with commands such asthe following:>> title( ’plot of v versus t’)>> xlabel (’Values of t’)>> ylabel (’Values of v’)>> grid

Page 9: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.9

Graphics

• The plot command displays a solid line by default

• If you want to plot each point with a symbol, you caninclude a specifier enclosed in single quotes in the plotfunction

Page 10: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.10

Graphics

• For example, if you want to use open circles enter>> plot (t, v, ’o’)

• MATLAB allows you to display more than one data set onthe same plot. For example, if you want to connect eachdata marker with a straight line you could type>> plot (t, v, t, v, ’o’)

Page 11: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.11

Graphics

• There are other features of graphics that are useful—forexample, plotting objects instead of lines, families ofcurves plots, plotting on the complex plane, multiplegraphs windows, log-log or semilog plots,three-dimensional mesh plots, and contour plots.

Page 12: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.12

Help

• The MATLAB package includes an extensive Help facilitythat can be accessed by clicking on the Help menu in thecommand window

• It also provides access to a number of instructive demos

• Help is also available in interactive mode by typing the helpcommand followed by the name of a command or function

• If you do not know the name, you can use the lookforcommand to search the MATLAB Help files foroccurrences of text

Page 13: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.13

Help

• For example, suppose that you want to find all thecommands and functions that relate to logarithms, youcould enter>> lookfor logarithm

• You can obtain help from The Math Works, Inc., website atwww.mathworks.com, and other links on the coursewebsite

• Sometimes, if you can’t figure out why MATLAB is spewingout error messages at you, just ask it why - it may help...

Page 14: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.14

Programming with MATLAB

Objectives

• Learn how to create well-documented M-files in the editwindow and invoke them from the command window

• Understand how to set up M-files so that they interactivelyprompt users for information and display results in thecommand window

• Learn how to write clear and well-documented M-files byemploying structured programming constructs toimplement logic and repetition

• Understand what is meant by vectorization and why it isbeneficial

• Understand how functions can be passed to M-files.

Page 15: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.15

A free-falling Bungee Jumper

Example problem

Page 16: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.16

Example problem

• We can use a force balance to develop a mathematicalmodel to predict the fall velocity of a bungee jumper

• This model takes the form of the following differentialequation:

dvdt

= g − cm

v (1)

• The numerical solution of this equation could beobtained with Euler’s method:

v(ti+1) = v(ti) +dvi

dt∆t (2)

• This equation can be implemented repeatedly to computevelocity as a function of time

• However, to obtain good accuracy, many small steps mustbe taken

• With the aid of MATLAB, such extremely laborious andtime consuming calculations can be performed easily

Page 17: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.17

M-Files

• The most common way to operate MATLAB is by enteringcommands one at a time in the command window

• M-files provide an alternative way of performing operationsthat greatly expand MATLAB’s problem-solving capabilities

• An M-file contains a series of statements that can be runall at once

• The nomenclature "M-file" comes from the fact that suchfiles are stored with a . m extension

• M-files come in two flavors:

• script files

• function files

Page 18: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.18

Script files

• A script file is merely a series of MATLAB commands thatare saved on a file

• The script can be executed by typing the file name in thecommand window or by invoking the menu selections inthe edit window: Debug, Run

Example

Problem Statement:

Develop a script file to compute the velocity of the free-fallingbungee jumper.

Solution:

• Open the editor with the menu selection: File, New, M-file

Page 19: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.19

Solution contd...

• Type in the following statements to compute the velocity ofthe free-falling bungee jumper at a specific time:

g = 9.81; m=8.1; t = 12; c = 0.25;

v = (g*m/c)*(1 - exp(-(c/m)*t))

• Save the file as scriptdemo.m

• Return to the command window and type in: scriptdemo

• Remember to set the path so MATLAB can find the M-file!

Page 20: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.20

Function files

• Function files are M-files that start with the wordfunction

• In contrast to script files, they can accept inputarguments and return outputs

• They are analogous to user-defined functions inprogramming languages such as Fortran, Visual Basic orC

• The syntax for the function file can be representedgenerally as

function outvar = funcname(arglist)% helpcommentsstatementsoutvar = value

where the various terms are explained below.

Page 21: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.21

Function files

function outvar = funcname(arglist)% helpcommentsstatementsoutvar = value

1 outvar = the name of the output variable,

2 funcname = the function’s name,

3 arglist = the function’s argument list (i.e.,

comma-delimited values that are passed into the function),

4 helpcomments = text that provides the user with

information regarding the function (these can be invoked

by typing Help funcname in the command window),

5 statements = MATLAB statements that compute the

value that is assigned to outvar

Page 22: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.22

Function files

• The M-file should be saved as funcname.m

• The function can then be run by typing funcname in the

command window as illustrated in the following example

• Even though MATLAB is case-sensitive, your computer’s

operating system may not be. Whereas MATLAB would

treat function names like freefallvel and

FreeFallVel as two different variables, your operating

system might not

Page 23: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.23

Example

Problem Statement:

As in the previous example, compute the velocity of the

free-falling bungee jumper, but now use a function file for

the task

Solution:

Type the following statements in the file editor:

function velocity = freefallvel(m, c, t)% freefallvel(m, c, t)% computes the free-fall velocity (mps)% of an object with second-order drag.% input:% m = mass (kg)% c = drag coefficient (kg/m)% t = time (s)

Page 24: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.24

Solution contd....

% output:% velocity = downward velocity (m/s)g = 9.81; % acceleration of gravityvelocity = (g*m/c)*(1 - exp(-(c/m)*t));

• Save the file as freefallvel.m

• To invoke the function, return to the command window andtype:freefallvel(8.1,0.25,12)

• To invoke the help comments type:help freefallvel

• The first few lines of all m-files begin with a “%" sign,which indicates a comment statement

• All comments are ignored by MATLAB

Page 25: MATLAB2 Beamer

Lecture Aims

Built-in functions

Graphics

Help

Programming withMATLABObjectives

Example problem

M-FilesScript files

Function files

Example

N.M. 2.25

• Comments have at least two very important uses:

• They can help other users (and very frequently, yourself!)understand what is going on.

• They can be used to “block" out lines of code that you don’twant executed.

• Function M-files can return more than one result

• In such cases, the variables containing the results arecomma-delimited and enclosed in brackets

• For example, the following function, stats.m, computesthe mean and the standard deviation of a vector:

function [mean, stdev] = stats(x)n = length (x);mean = sum(x)/n;stdev = sqrt(sum((x-mean).^2/(n-1)));