+ All Categories
Home > Documents > MATLAB Ch 3 – Functions & Files

MATLAB Ch 3 – Functions & Files

Date post: 23-Feb-2016
Category:
Upload: nancy
View: 84 times
Download: 1 times
Share this document with a friend
Description:
MATLAB Ch 3 – Functions & Files . EGR1302. Outline. Introduction Elementary mathematical operations User-defined functions Working with data files. Introduction. Review from Ch 1 MATLAB mathematical functions Pair of parentheses after function name encloses function’s argument - PowerPoint PPT Presentation
Popular Tags:
42
MATLAB Ch 3 – Functions & Files EGR1302
Transcript
Page 1: MATLAB Ch 3 – Functions & Files

MATLAB Ch 3 – Functions & Files EGR1302

Page 2: MATLAB Ch 3 – Functions & Files

Outline Introduction Elementary mathematical

operations User-defined functions Working with data files

Page 3: MATLAB Ch 3 – Functions & Files

Introduction Review from Ch 1

MATLAB mathematical functions Pair of parentheses after function

name encloses function’s argument Can be part of mathematical

expression Users can define functions MATLAB has commands and

functions for managing the work session

Page 4: MATLAB Ch 3 – Functions & Files

Introduction MATLAB has many built-in

functions Users may define functions

Convenient use Advanced function capability

Function handles Anonymous functions Subfunctions Nested functions

MATLAB allows input/output of data files

Page 5: MATLAB Ch 3 – Functions & Files

ELEMENTARY MATHEMATICAL FUNCTIONS

Section 3.1

Page 6: MATLAB Ch 3 – Functions & Files

Finding relevant functions Command – lookfor

Seeks the word in the help descriptions of the MATLAB help system

If user does not know the name of function

>> lookfor imaginaryi - Imaginary unit.j - Imaginary unit.complex - Construct complex result

from real and imaginary parts.

imag - Complex imaginary part.

Page 7: MATLAB Ch 3 – Functions & Files

Finding relevant functions

Page 8: MATLAB Ch 3 – Functions & Files

Finding relevant functions Command – disp

If user knows correct spelling of a MATLAB function

Same output as selecting complex hyperlink after using lookfor command >> disp complex

Page 9: MATLAB Ch 3 – Functions & Files

Tables 3.1-1, 3.1-2, 3.1-3 List of some common

mathematical functions (pp. 142, 146, 148) Exponential & logarithmic Complex number Numeric Trigonometric Hyperbolic

Page 10: MATLAB Ch 3 – Functions & Files

Example – complex functions

>> x=-3+4i;>> y=6-8i;>> mag_x = abs(x)mag_x = 5>> mag_y = abs(y)mag_y = 10>> mag_product = abs(x*y)mag_product = 50

Page 11: MATLAB Ch 3 – Functions & Files

>> angle_x = angle(x)angle_x = 2.2143>> angle_y = angle(y)angle_y = -0.9273>> sum_angles = angle_x + angle_ysum_angles = 1.2870>> angle_product = angle(x*y)angle_product = 1.2870

Example – complex functions

Page 12: MATLAB Ch 3 – Functions & Files

USER-DEFINED FUNCTIONS

Section 3.2

Page 13: MATLAB Ch 3 – Functions & Files

Functions files Differences between script &

functions M-files All functions variables are local

Values available only within function Useful when repeating a set of

commands multiple times Building blocks of larger programs

First line in function function definition line

List of inputs and outputs

Page 14: MATLAB Ch 3 – Functions & Files

Function definition line Distinguishes function from script

function – must be lower case Output variables must be enclosed

in square brackets Input variables must be enclosed in

parentheses func_name must be same as name

of M-file Use exist function before naming a

function

function[output vars]=func_name(input vars)

Page 15: MATLAB Ch 3 – Functions & Files

>> fun(3,7)ans = 303

>> z??? Undefined function or variable 'z'.>> u??? Undefined function or variable 'u'.

Simple function examplefunction z = fun(x,y)u = 3*x;z = u + 6*y.^2;

>> z = fun(3,7)z = 303

>> y = [3 4 5];>> z = fun(y,7)z = 303 306 309

Page 16: MATLAB Ch 3 – Functions & Files

Functions Suppress output of function by

putting semicolon after the function call

Only order of arguments is important, not names of arguments

Arrays can be used as input arguments

May have more than one output

Page 17: MATLAB Ch 3 – Functions & Files

Variations in function line One input, one output:

Brackets are optional

Two inputs, one output

One input, two outputs

No named output: function sqplot(side)

function [area_square] = square(side)OR

function area_square = square(side)

function [volume_box] = box(height,width,length)

function [area_circle,circumf] = circle(radius)

function sqplot(side)

Page 18: MATLAB Ch 3 – Functions & Files

>> r = [3 4 5];>> [A, C] = circle(r)A = 28.2743 50.2655 78.5398C = 18.8496 25.1327 31.4159

2nd simple function examplefunction [A, C] = circle(r)A = pi*r.^2;C = 2*pi*r;

>> [A, C] = circle(4)A = 50.2655C = 25.1327

Page 19: MATLAB Ch 3 – Functions & Files

Comments in functions Comment lines, starting with %,

may be placed anywhere in function file

If user types help to obtain information about function All comment lines immediately

following function definition line up to first blank or executable line is displayed

If user types lookfor command First comment line is displayed

Page 20: MATLAB Ch 3 – Functions & Files

Local variables Names of input variables given in

function are local to the function Other variable names can be used

when calling the function All variables inside a function are

erased after the function finishes executing Except when the same variable

names appear in the output variable list used in the function call

Page 21: MATLAB Ch 3 – Functions & Files

Global variables global command declares

certain variables global Their values are available to the

basic workspace and to other functions that declare these variables global.

Any assignment to those variables, in any function or in the base workspace, is available to all the other functions declaring them global.

global a x q

Page 22: MATLAB Ch 3 – Functions & Files

Finding the zeros of a function

function is a string containing the name of the function

x0 is a user-supplied guess for the zero

Returns a value of x that is near x0 Identifies only points where the

function crosses the x-axis Not points where the function just

touches the axis.

fzero(‘function’, x0)

>> fzero('cos',2)ans = 1.5708

Page 23: MATLAB Ch 3 – Functions & Files

Using fzero with user-defined functions To find the zeros of more

complicated functions, it is more convenient to define the function in a function filefunction y = f1(x)y = x + 2*exp(-x) - 3;

>> x = fzero('f1',-1)x = -0.5831>> x = fzero('f1',2)x = 2.8887

Page 24: MATLAB Ch 3 – Functions & Files

Finding the minimum of a function function is a string containing

the name of the function Returns a value of x that minimizes

the function in the interval x1 ≤ x ≤ x2

fminbnd(‘function’, x1,x2)

>> fminbnd('cos', 0,4)ans = 3.1416

Page 25: MATLAB Ch 3 – Functions & Files

Finding the minimum of a function For functions of more than one

variable

function is a string containing the name of the function

Vector x0 is a guess that must be supplied by the user.

fminsearch(‘function’, x0)

>> fminsearch('f4',[0,0])ans = -0.7071 0.0000

function f = f4(x)f = x(1).*exp(-x(1).^2-x(2).^2);

Page 26: MATLAB Ch 3 – Functions & Files

Design optimization example Example 3.2-2, p. 161

Page 27: MATLAB Ch 3 – Functions & Files

WORKING WITH DATA FILES

Section 3.4

Page 28: MATLAB Ch 3 – Functions & Files

Importing data files Typical ASCII file

Header lines One or more lines of text Contain comments, creation date,

column headings Data

Arranged in rows & columns Each number in a row may be

separated Spaces Commas Tab

Page 29: MATLAB Ch 3 – Functions & Files

Importing data files Importing an externally

generated file in ASCII format Matlab can not import data that is

separated (i.e., delimited) by commas

To import a comma-delimited ASCII file, some pre-processing is required

First, open data file in a text editor (e.g., Notepad)

Second, delete the text header lines Third, replace each comma with at

least one space (i.e., use Replace function)

Page 30: MATLAB Ch 3 – Functions & Files

Importing data files Importing an externally

generated file in ASCII format

Matrix is generated Name of matrix is filename with

extension stipped off

This command creates a matrix named “tensile_test”

load filename

load tensile_test.txt

Page 31: MATLAB Ch 3 – Functions & Files

Importing data files Excel spreadsheets may be

imported into Matlab Save Excel file in 2003 format

(i.e., .xls extension)

Imports file into array A

Imports all numeric data into array A and all text data into array B

A = xlsread(‘filename’)

[A, B] = xlsread(‘filename’)

Page 32: MATLAB Ch 3 – Functions & Files

Import Wizard Allows for importing a variety of

ASCII file formats Space-delimited files Mixed text and numeric files Files with text headers Files with non-space delimiters

Commas Semi-colons Tabs

Page 33: MATLAB Ch 3 – Functions & Files

Import Wizard What you must know before you

may import the data file How many data items are in each

row? Are the data items numeric, text

strings, or a mixture of both types? Does each row or column have a

descriptive text header? What character is used as the

delimiter that separates items in each row into columns?

Page 34: MATLAB Ch 3 – Functions & Files

Import Wizard Caution

Import Wizard overwrites any existing variable in the workspace with no warning message!

Dialog boxes ask you to: Specify the name of the file you

want to import Specify the delimiter used in the file Select the variables that you want

to import

Page 35: MATLAB Ch 3 – Functions & Files

Import Wizard

Page 36: MATLAB Ch 3 – Functions & Files

End of Chapter 3

Page 37: MATLAB Ch 3 – Functions & Files

Slides that I do not plan to use

Page 38: MATLAB Ch 3 – Functions & Files

Outline Introduction Elementary mathematical

operations User-defined functions Advanced function programming Working with data files

Page 39: MATLAB Ch 3 – Functions & Files

ADVANCED FUNCTION PROGRAMMING

Section 3.3

Page 40: MATLAB Ch 3 – Functions & Files

Function handles Create a function handle to any

function by using the at sign, @, before the function name. Name the handle Use the handle to reference the

function

sine_handle is a user-selected name for the handle

>>sine_handle = @sin;

Page 41: MATLAB Ch 3 – Functions & Files

Function handles A common use

Pass the function as an argument to another function

Example - plot sin x over 0 £ x £ 6 as follows:

Cumbersome way to plot the sine function

However, the concept can be extended to create a general purpose plotting function that accepts a function as an input

>>plot([0:0.01:6],sine_handle,[0:0.01:6])

Page 42: MATLAB Ch 3 – Functions & Files

Function handles function x = gen_plot(fun_handle, interval)

plot(interval, fun_handle, interval)

You may call this function to plot the sin x over 0 £ x £ 6 as follows:

>>gen_plot(sine_handle,[0:0.01:6])

or >>gen_plot(@sin,[0:0.01:6])


Recommended