Understanding Scripts and Functions in Matlab Programming, Study notes of Engineering

An overview of the differences between scripts and functions in matlab programming. It covers the use of script files, script side-effects, functions, function input and output, and various examples of using functions and the disp and fprintf functions. The document also discusses vectorization and matlab's features to solve recurring programming problems.

Typology: Study notes

Pre 2010

Uploaded on 07/30/2009

koofers-user-sz1-1
koofers-user-sz1-1 🇺🇸

9 documents

1 / 73

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Matlab Programming
Gerald W. Recktenwald
Department of Mechanical Engineering
Portland State University
These slides are a supplement to the book Numerical Methods with
Matlab: Implementations and Applications, by Gerald W. Recktenwald,
c
2001, Prentice-Hall, Upper Saddle River, NJ. These slides are c
2001 Gerald W. Recktenwald. The PDF version of these slides may
be downloaded or stored or printed only for noncommercial, educational
use. The repackaging or sale of these slides in any form, without written
consent of the author, is prohibited.
The latest version of this PDF file, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.
Version 0.97 August 28, 2001
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49

Partial preview of the text

Download Understanding Scripts and Functions in Matlab Programming and more Study notes Engineering in PDF only on Docsity!

Matlab Programming

Gerald W. Recktenwald Department of Mechanical Engineering Portland State University [email protected]

These slides are a supplement to the book Numerical Methods with Matlab: Implementations and Applications, by Gerald W. Recktenwald, ©c 2001, Prentice-Hall, Upper Saddle River, NJ. These slides are ©c 2001 Gerald W. Recktenwald. The PDF version of these slides may be downloaded or stored or printed only for noncommercial, educational use. The repackaging or sale of these slides in any form, without written consent of the author, is prohibited.

The latest version of this PDF file, along with other supplemental material for the book, can be found at www.prenhall.com/recktenwald.

Version 0.97 August 28, 2001

Overview

  • Script m-files

 Creating  Side effects

  • Function m-files  Syntax of I/O parameters  Text output  Primary and secondary functions
  • Flow control

 Relational operators  Conditional execution of blocks  Loops

  • Vectorization

 Using vector operations instead of loops  Preallocation of vectors and matrices  Logical and array indexing

  • Programming tricks  Variable number of I/O parameters  Indirect function evaluation  Inline function objects  Global variables

Script Files

  • Not really programs  No input/output parameters  Script variables are part of workspace
  • Useful for tasks that never change
  • Useful as a tool for documenting homework:  Write a function that solves the problem for arbitrary parameters  Use a script to run function for specific parameters required by the assignment

Free Advice: Scripts offer no advantage over functions. Functions have many advantages over scripts. Always use functions instead of scripts.

Script to Plot tan(θ) ( 1 )

Enter statements in file called tanplot.m

  1. Choose New... from File menu
  2. Enter lines listed below

Contents of tanplot.m:

theta = linspace(1.6,4.6); tandata = tan(theta); plot(theta,tandata); xlabel(’\theta (radians)’); ylabel(’tan(\theta)’); grid on; axis([min(theta) max(theta) -5 5]);

  1. Choose Save... from File menu Save as tanplot.m
  2. Run it

tanplot

Script Side-Effects ( 1 )

All variables created in a script file are added to the workplace. This may have undesirable effects because

  • Variables already existing in the workspace may be overwritten
  • The execution of the script can be affected by the state variables in the workspace.

Example: The easyplot script

% easyplot: Script to plot data in file xy.dat % Load the data D = load(’xy.dat’); % D is a matrix with two columns x = D(:,1); y = D(:,2); % x in 1st column, y in 2nd column plot(x,y) % Generate the plot and label it xlabel(’x axis, unknown units’) ylabel(’y axis, unknown units’) title(’Plot of generic x-y data set’)

Script Side-Effects ( 2 )

The easyplot script affects the workspace by creating three variables:

clear who (no variables show) easyplot who

Your variables are:

D x y

The D, x, and y variables are left in the workspace. These generic variable names might be used in another sequence of calculations in the same Matlab session. See Exercise 10 in Chapter 4.

Function m-files ( 1 )

  • Functions are subprograms:

 Functions use input and output parameters to communicate with other functions and the command window  Functions use local variables that exist only while the function is executing. Local variables are distinct from variables of the same name in the workspace or in other functions.

  • Input parameters allow the same calculation procedure (same algorithm) to be applied to different data. Thus, function m-files are reusable.
  • Functions can call other functions.
  • Specific tasks can be encapsulated into functions. This modular approach enables development of structured solutions to complex problems.

Function m-files ( 2 )

Syntax:

The first line of a function m-file has the form:

function [outArgs] = funName(inArgs)

outArgs are enclosed in [ ]

  • outArgs is a comma-separated list of variable names
  • [ ] is optional if there is only one parameter
  • functions with no outArgs are legal

inArgs are enclosed in ( )

  • inArgs is a comma-separated list of variable names
  • functions with no inArgs are legal

Function Input and Output ( 2 )

twosum.m

function twosum(x,y) % twosum Add two matrices % and print the result x+y

threesum.m

function s = threesum(x,y,z) % threesum Add three variables % and return the result s = x+y+z;

addmult.m

function [s,p] = addmult(x,y) % addmult Compute sum and product % of two matrices s = x+y; p = x*y;

Function Input and Output Examples ( 3 )

Example: Experiments with twosum:

twosum(2,2) ans = 4

x = [1 2]; y = [3 4]; twosum(x,y) ans = 4 6

A = [1 2; 3 4]; B = [5 6; 7 8]; twosum(A,B); ans = 6 8 10 12

twosum(’one’,’two’) ans = 227 229 212

Notes: 1. The result of the addition inside twosum is exposed because the x+y expression does not end in a semicolon. (What if it did?)

  1. The strange results produced by twosum(’one’,’two’) are obtained by adding the numbers associated with the ASCII character codes for each of the letters in ‘one’ and ‘two’. Try double(’one’) and double(’one’) + double(’two’).

Function Input and Output Examples ( 5 )

Example: Experiments with threesum:

a = threesum(1,2,3) a = 6

threesum(4,5,6) ans = 15

b= threesum(7,8,9);

Note: The last statement produces no output because the assignment expression ends with a semicolon. The value of 24 is stored in b.

Function Input and Output Examples ( 6 )

Example: Experiments with addmult:

[a,b] = addmult(3,2) a = 5 b = 6

addmult(3,2) ans = 5

v = addmult(3,2) v = 5

Note: addmult requires two return variables. Calling addmult with no return variables or with one return variable causes undesired behavior.

Text Input and Output

It is usually desirable to print results to the screen or to a file. On rare occasions it may be helpful to prompt the user for information not already provided by the input parameters to a function.

Inputs to functions:

  • input function can be used (and abused!).
  • Input parameters to functions are preferred.

Text output from functions:

  • disp function for simple output
  • fprintf function for formatted output.

Prompting for User Input

The input function can be used to prompt the user for numeric or string input.

x = input(’Enter a value for x’);

yourName = input(’Enter your name’,’s’);

Prompting for input betrays the Matlab novice. It is a nuisance to competent users, and makes automation of computing tasks impossible.

Free Advice: Avoid using the input function. Rarely is it necessary. All inputs to a function should be provided via the input parameter list. Refer to the demonstration of the inputAbuse function in § 3.3.1.