Sie sind auf Seite 1von 32

SCRIPTS, FLOW CONTROL, AND DATA STRUCTURES

ENSC 180 Introduction to Engineering Analysis Tools


School of Engineering Science Simon Fraser University Burnaby, BC, Canada

Ensc180 Calendar
Unit What 1 2 3 4 5 6 7 8 9 10 11 12 Introduction to MATLAB Flow control & Data Structures Plotting Strings & File IO Complex Numbers Combinatorics Linear Algebra Statistics & Data Analysis Polynomial Approximation, Curve Fitting Root Finding, Numerical Differentiation Numerical Integration MATLAB executable files
2

When Sat Jan 25 Sat Feb 1 Fri Feb 7 Fri Feb 22 Fri Mar 7

What Assignment 1 Assignment 2 Mid-Term 1 Assignment 3 Mid-Term 2

Where CANVAS CANVAS Room B9200, 2:30pm CANVAS Room B9200, 2:30pm CANVAS CANVAS CANVAS CANVAS Room TBA, 8:30am

Sat Mar 15 Assignment 4 Sat Mar 22 Assignment 5 Sat Mar 29 Assignment 6 Sat Apr 5 Assignment 7 Thu Apr 17 Final Exam

ENSC 180 Introduction to Engineering Analysis Tools

SCRIPTS

A script is simply a file containing a series of MATLAB commands. Until now, we have been using MATLAB terminal to enter commands. For larger, more complicated tasks, it is better to write all commands in a script file. Upon running the script, all the commands within it will be performed sequentially just like any C/C++ program. Any MATLAB command (i.e., anything that can run in the terminal) can be placed in a script; no declarations and no begin/end delimiters are necessary. Scripts need to be saved to a .m file before they can be run. You may wish to setup folders to keep scripts and functions organized. In order to run a script, the current folder in MATLAB must be changed to the folder that contains the script (Command cd). Alternatively, this can be avoided by adding the folders path to MATLAB by using Environment Set Path (MATLAB R2012b).

ENSC 180 Introduction to Engineering Analysis Tools

SCRIPTS
Several advantages to using scripts over the command line include: User can automate tasks. Uses smart indentation to help read and write code more comfortably. Allows the use of breakpoints for debugging. Allows the use of the MATLAB profiler and tic/toc functions to analyze program performance. User can run individual pieces of code by highlighting a piece and pressing F9 (in addition to breakpoints, this makes debugging very convenient and easy). To remove previous variables from the workspace, you may wish to place the command clear all at the beginning of your script. The close all command may also be placed at the beginning if closing all figures is desired prior to running the script. It is good practice to use ; at the end of commands when writing scripts to inhibt unwanted output When a script is running the >> symbol at the terminal will disappear until it finishes, preventing any commands from being input. To terminate the script before conclusion and regain control, press Ctrl+C.

ENSC 180 Introduction to Engineering Analysis Tools

ELLIPSES

Word wrap for comments is automatically enabled in scripts so that each line fits in the viewable window to prevent the need for horizontal scrolling. Making use of ellipses ... can help make scripts more readable when there are long statements of code: A = [1 2 3 4 5 6; ... 6 5 4 3 2 1]; This can also be used to make long character strings by concatenating two shorter strings together: mystring = ['Accelerating the pace of ' ... 'engineering and science'];

ENSC 180 Introduction to Engineering Analysis Tools

CONDITIONAL STATEMENTS

Scripts can be made more effective when you are able to control which blocks of code are executed. MATLAB is capable of flow control just like any other language. The most basic flow control element is the if statement. a = 6; if a > 10 b = 0; elseif a < 3 b = 1; else b = 2; end The statements are evaluated only when the logical expressions are true. The elseif and else are optional.

ENSC 180 Introduction to Engineering Analysis Tools

FOR LOOPS

A for loop uses a counter to repeatedly execute the block of code within it. It follows the syntax: for index=values, statements, end. The values portion of the syntax can take several forms, one of which is: A = []; for ii = 2:2:8 A = [A ii] end ii ii ii ii = = = = 2 4 6 8 A A A A = = = = 2 2 2 2

4 4 4

6 6

In this case, the index ii is incremented by an optional step size until it reaches 8. A is initialized as an empty matrix and its size is constantly updated as we add to it during each iteration of the loop. Note that the name of the index variable is ii rather than the traditional i, commonly used in C/C++. Recall that i is reserved for the complex unit. Can create character indices as well, e.g. ii = 'a':'z'. The value of the index should never be modified by the statements inside the loop.

ENSC 180 Introduction to Engineering Analysis Tools

FOR LOOPS

values can also be defined without the use of the colon operator: A = zeros(1,3); %pre-allocate space k = 1; %count loop iterations valueMatrix = [1 2 3; 5 6 7]; for jj = valueMatrix fprintf('iteration %d:\n', k) A(k) = jj(1) + jj(2); jj, A %display variables on terminal k = k + 1; end Here, the loop index is a column vector obtained from subsequent columns of the matrix valueMatrix on each iteration. Even if column vector indices are not desired, this method allows the use of irregular loop indices.
ENSC 180 Introduction to Engineering Analysis Tools 8

iteration 1: jj = 1 5 A = 6 0 0

iteration 2: jj = 2 6 A = 6 8 0

iteration 3: jj = 3 7 A = 6 8 10

PRE-ALLOCATING SPACE TO VARIABLES


Note that in the previous example, we pre-allocated space to matrix A rather than letting MATLAB resize it on every iteration. Use functions like length and size along with the colon operator to determine loop indices after pre-allocating space. A tic for ii = 1:2000 for jj = 1:2000 A(ii,jj) = ii + jj; end end toc B tic A = zeros(2000, 2000); for ii = 1:size(A,1) for jj = 1:size(A,2) A(ii,jj) = ii + jj; end end toc Elapsed time is 2.261 seconds

Elapsed time is 12.357 seconds

Which of the two solutions will compute faster?


ENSC 180 Introduction to Engineering Analysis Tools

PRE-ALLOCATING SPACE TO VARIABLES


Note that in the previous example, we pre-allocated space to matrix A rather than letting MATLAB resize it on every iteration (computationally expensive). For very large loops, it is good practice to always pre-allocate space: A B tic for ii = 1:2000 for jj = 1:2000 A(ii,jj) = ii + jj; end end toc tic A = zeros(2000, 2000); for ii = 1:size(A,1) for jj = 1:size(A,2) A(ii,jj) = ii + jj; end end toc Elapsed time is 2.261 seconds

Elapsed time is 12.357 seconds

Use functions like length and size along with the colon operator to determine loop indices after pre-allocating space.
ENSC 180 Introduction to Engineering Analysis Tools

10

WHILE LOOPS

A while loop repeats for as long as the condition remains true. This can be very useful for things such as numerical approximation, where we arent sure of the exact number of iterations. E.g.: we want to approximate using Newtons method and we want the estimate to be within 10-32 of the actual value: x = 2; k = 0; error = inf; error_threshold = 1e-32; while error > error_threshold x = x - sin(x)/cos(x); error = abs(x - pi); k = k + 1; end

>> x x = 3.141592653589793 >> k k = 6

We see that it takes 6 iterations to achieve our desired precision using an initial estimate of x = 2.

ENSC 180 Introduction to Engineering Analysis Tools

11

BREAK

The command break terminates the execution of for or while loops. Control passes to the statement that follows the end of that loop. x = 2; k = 0; error = inf; error_threshold = 1e-32; while error > error_threshold if k > 3 break end x = x - sin(x)/cos(x); error = abs(x - pi); k = k + 1; end >> x x = 3.140943912317635 >> error error = 6.4874e-04 >> k k = 4

Can be useful in iterative methods where convergence is not guaranteed.

ENSC 180 Introduction to Engineering Analysis Tools

12

SWITCH STATEMENTS

In a switch statement, the input is matched against several different values and a block of code is executed for the case where the match is correct: x = 't'; switch x case 2 disp('x case -1 disp('x case 't' disp('x otherwise disp('x end

is 2') is -1') is the character t') is not 2, -1, or t')

x is the character t

ENSC 180 Introduction to Engineering Analysis Tools

13

TRY/CATCH STATEMENTS

Attempts to evaluate an expression; if an error occurs, the statement inside the catch block is executed. After the error is caught, the script continues after the end of the try statement. a = 1:5; b = 1:3; for ii = 1:length(a) try c(ii) = a(ii) + b(ii) catch disp('b is too small') end end c = 2 c = 2 c = 2 4 6 4

b is too small b is too small In this example, b only has 3 elements so an error occurs when the script attempts to access the 4th and 5th element. By using try/catch, MATLAB no longer terminates the script at this error.

ENSC 180 Introduction to Engineering Analysis Tools

14

Scripts and Functions

There are two kinds of program files: Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace. When you invoke a script, MATLAB simply executes the commands found in the file. Functions, which can accept input arguments and return output arguments. Internal variables are local to the function. When you call a function, MATLAB only executes the portion of the function file related to the function and eventual subfunctions

ENSC 180 Introduction to Engineering Analysis Tools

15

FUNCTIONS

Functions are useful for automating frequently used tasks and subroutines. For example, we can write a script to calculate the area of a triangle: b = 5; h = 3; a = 0.5*(b.* h) a = 7.5000

To perform this calculation again for a different triangle, we would have to modify the values of b and h in the script and re-run it. Rather than doing this, we can simply convert this task into a function [1]. function a = triarea(b, h) a = 0.5*(b.* h); end The calculation can now be performed repeatedly without any modifications: a1 = triarea(1,5) a2 = triarea(2,10) a1 = 2.5000 a2 = 10

ENSC 180 Introduction to Engineering Analysis Tools

16

FUNCTION FILES

Functions must be defined in an independent file, that must be saved in the work folder MATLAB files can contain code for more than one function. The first function in the file (the main function) is visible to functions in other files, or you can call it from the command line. Additional functions within the file are called local functions. Local functions are only visible to other functions in the same file. They are equivalent to subroutines in other programming languages, and are sometimes called subfunctions. Local functions can occur in any order, as long as the main function appears first. Each function begins with its own function definition line.

ENSC 180 Introduction to Engineering Analysis Tools

17

FUNCTIONS

Functions have their own independent workspaces and everything that occurs inside is hidden from the main workspace. From the previous example, if my main workspace has a variable b already defined, calling triarea will not interfere with this variable even though we use a variable also called b inside of it. >> b = 99; >> a3 = triarea(2,4); >> b b = 99

Finally, any lines after the function name which begin with % will serve as the help text when the function is called using the help command. function a = triarea(b, h) % This function calculates % the area of a triangle. % INPUTS: b - base, h - height % OUTPUTS: a area a = 0.5*(b.* h); end
ENSC 180 Introduction to Engineering Analysis Tools

>> help triarea This function calculates the area of a triangle. INPUTS: b - base, h - height OUTPUTS: a - area
18

FUNCTIONS
Solution A: Running a simple Script b = 5; h = 3; a = 0.5*(b.* h)

a = 7.5000

Solution B: Calling a Function function a = triarea(b, h) a = 0.5*(b.* h); end a1 = triarea(5,3) a1 = 7.5000

Which of the two solutions is faster ?

ENSC 180 Introduction to Engineering Analysis Tools

19

FUNCTIONS
Solution A: Running a simple Script b = 5; h = 3; a = 0.5*(b.* h) Elapsed time is 0.000288 seconds. Solution B: Calling a Function function a = triarea(b, h) a = 0.5*(b.* h); end a1 = triarea(5,3) Elapsed time is 0.0003390 seconds. The first solution is faster as it does not involve seeking the file system for the function and calling it (control overhead). Functions are useful for code readability and efficiency, but do not speed up computation; on the contrary, they involve a little overhead
ENSC 180 Introduction to Engineering Analysis Tools

a = 7.5000

a1 = 7.5000

20

FUNCTION HANDLES

Function handles provide a way to create anonymous functions, i.e., one line expression functions that do not have to be defined in .m files. A function handle is a MATLAB data type and can therefore be passed into other functions to be called indirectly.
1

>> f = @(x) exp(-2*x); >> x = 0:0.1:2; >> plot(x, f(x)) We have assigned the function e-2x to function handle f and evaluated it at each point in vector x. To integrate from 0.2 to 0.8, we can use f as an input argument to the MATLAB function integral: >> integral(f, 0.2, 0.8) ans = 0.2342
ENSC 180 Introduction to Engineering Analysis Tools

0.8 0.6 f(x) 0.4 0.2 0 0

e-2x

0.5

1 x

1.5

21

CELL ARRAYS

In a matrix, each element contains a single value and all elements in the matrix must be of a single type, e.g. double, char, logical, etc. A cell array is a data structure with indexed containers (like the elements of a matrix) called cells. Each cell, can store any type of data and can vary in size. Cell arrays can be created using the same syntax as a matrix, except curly brackets {} are used instead of square brackets []. >> A = {[1 2; 3 4], 27; 'Alice', {1, 2, 3}} A = [2x2 double] [ 27] 'Alice' {1x3 cell} In this example, A is a 2-by-2 cell array containing different types of arrays with different sizes.

ENSC 180 Introduction to Engineering Analysis Tools

22

CELL ARRAYS

To retrieve the contents of a cell, use indexing with curly brackets. >> A = {[1 2; 3 4], 27; 'Alice', {1, 2, 3}} >> B = A{1,1} B = 1 2 3 4 To retrieve a cell itself, use indexing with round brackets. >> C = A(1,:) C = [2x2 double]

[27]

Here, C is a 1-by-2 cell array.

ENSC 180 Introduction to Engineering Analysis Tools

23

STRUCTURES

Like the cell array, a structure is another method of storing heterogeneous data. A structure is composed of data containers called field, which are accessed by strings. For example, we want to store student assignment grades in a structure: student.name = 'John Doe'; student.id = 'jdo2@sfu.ca'; student.number = 301073268; student.grade = [100, 75, 73; ... 95, 91, 85.5; ... 100, 98, 72]; student = name: id: number: grade: 'John Doe' 'jd2@sfu.ca' 301073268 [3x3 double]

ENSC 180 Introduction to Engineering Analysis Tools

24

STRUCTURES

Records for additional students can be added by including an index after the name of the structure: student(2).name = 'Ann Lane'; student(2).id = 'aln4@sfu.ca'; student(2).number = 301078853; student(2).grade = [95, 95, 100; 100, 82, 85; 90, 97, 100]; student = 1x2 struct array with fields: name id number grade

ENSC 180 Introduction to Engineering Analysis Tools

25

CELL ARRAYS VS. STRUCTURES

Choosing between cell arrays and structures is mostly a matter of personal preference and code clarity. The containers of a cell array are referred to by their index, whereas the containers of a structure are referred to by their names. student_data(1,:) [100, 75, 73; 95, student_data(2,:) [95, 100, 90; 95, student_data = 'John Doe' 'Ann Lane' = {'John Doe', 'jdo2@sfu.ca', 301073268, ... 91, 85.5; 100, 98, 72]}; = {'Ann Lane', 'aln4@sfu.ca', 301078853, ... 82, 97; 100, 85, 100]};

'jdo2@sfu.ca' 'aln4@sfu.ca'

[301073268] [301078853]

[3x3 double] [3x3 double]

Here, we accomplish what we did previously using a cell array. Rather than fetching the 2nd students no. by student(2).number, we would do student_data{2,3}, since column 3 is where student numbers are stored. Since this is not as intuitive, we may conclude that a structure was a better choice.
ENSC 180 Introduction to Engineering Analysis Tools 26

MULTIDIMENSIONAL ARRAYS

A normal 2D data structure, such as a matrix or cell array, has rows as the 1st dimension and columns as the 2nd. We may add a 3rd dimension, sometimes called a page, by adding another index.

[2]

Just as we transitioned from a 1D vector/array to a 2D matrix, the same rules still apply for 3D matrices and data structures. Additional indices can be added (dim1, dim2, dim3, ..., dimN) for N-dimensional matrices.

ENSC 180 Introduction to Engineering Analysis Tools

27

MULTIDIMENSIONAL ARRAYS

There are various ways of creating multidimensional arrays: One way is to first create a 2D array and then extend it with indexing: >> A = [1 2; 3 4]; >> A(:,:,2) = [9 8; 7 6] A(:,:,1) = 1 2 3 4 A(:,:,2) = 9 8 7 6

If we assign a scalar to a new page, MATLAB fills the entire dimension with that scalar: >> A(:,:,3) = 5

A(:,:,1) = 1 2 3 4

A(:,:,2) = 9 8 7 6

A(:,:,3) = 5 5 5 5

ENSC 180 Introduction to Engineering Analysis Tools

28

MULTIDIMENSIONAL ARRAYS

They can also be generated using MATLAB functions like randn and zeros, e.g., to create a 4x5x2 array of zeros: A = zeros(4,5,2). The repmat function can be used to replicate a matrix across multiple dimensions. For example, to copy a matrix A across 4 pages in the 3rd dimension: >> A = [1 2; 3 4]; >> B = repmat(A, [1 1 4]) B(:,:,1) = 1 2 3 4 B(:,:,3) = 1 2 3 4 B(:,:,2) = 1 2 3 4 B(:,:,4) = 1 2 3 4

ENSC 180 Introduction to Engineering Analysis Tools

29

MULTIDIMENSIONAL ARRAYS
Sets of matrices can be concatenated along any dimension using the cat function C = cat(dim, A, B)

Examples of matrix concatenation on different dimensions: A = [ 1 2 ; 3 4 ] B = [ 5 6; 7 8]

ENSC 180 Introduction to Engineering Analysis Tools

30

C = cat(dim, A, B) C = cat(dim, A, B)

MULTIDIMENSIONAL ARRAYS

Sets of matrices can be concatenated along any dimension using the cat function C = cat(dim, A, B) >> A1 = [0 2; 4 6]; >> A2 = [1 3; 5 9]; >> B = cat(3, A1, A2) B(:,:,1) = 0 2 4 6 >> C = cat(4, B, B) C(:,:,1,1) = 0 2 4 6 C(:,:,1,2) = 0 2 4 6
ENSC 180 Introduction to Engineering Analysis Tools

B(:,:,2) = 1 3 5 9

C(:,:,2,1) = 1 3 5 9 C(:,:,2,2) = 1 3 5 9
31

BIBLIOGRAPHY

[1] MathWorks. (2013). Scripts vs. Functions [Online]. Available: http://www.mathworks.com/help/matlab/matlab_prog/scripts-and-functions.html [Accessed Sep. 30, 2013]. [2] MathWorks. (2013). Multidimensional Arrays [Online]. Available: http://www.mathworks.com/help/matlab/math/multidimensional-arrays.html [Accessed Sep. 30, 2013].

ENSC 180 Introduction to Engineering Analysis Tools

32

Das könnte Ihnen auch gefallen