Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Hong Kong Polytechnic University Industrial Centre 1 MatLAB Lesson 7 : M-file Programming I Edward Cheung Room W311g 2008.

Similar presentations


Presentation on theme: "The Hong Kong Polytechnic University Industrial Centre 1 MatLAB Lesson 7 : M-file Programming I Edward Cheung Room W311g 2008."— Presentation transcript:

1 The Hong Kong Polytechnic University Industrial Centre 1 MatLAB Lesson 7 : M-file Programming I Edward Cheung email: icec@polyu.edu.hk Room W311g 2008

2 2 Types of M-file Script M-file  doesn’t accept input argument  No return output argument  Operates on data in the workspace only  Useful for the automation of a series of commands that frequently needed – like macro Function M-files  Accept input argument and provide output return argument  Internal variables are local by default  Useful for building function Can be include in search path file  Set path or >> pathtool

3 3 Example of Script File %script M-file %This program shows how to create a script file start_th=0; end_th=2*pi; th=start_th:.1:end_th; x=sin(th); y=cos(th); plot(x,y); axis equal title('Sine vs. Cosine','fontsize',18) xlabel('Sine','fontsize',16) ylabel('Cosine','fontsize',16)

4 4 Example of Script File (cont.) >> save file as script_test.m >> script_test % run script file

5 5 Functions Types of functions  Built-in function  User-defined function Function files are created and edited like script files using the editor/debugger window file  New  M-file First line must be the function’s definition Syntax:-  function [output_arg]=fun_name (input_arg)  [] is not required for single output argument

6 6 Variables Local  The arguments and variables are valid for the function file only Global  We can make a variable recognized in different function files by using  >>global=variable_name All the variables in a function file are local Good practice is to minimize the use of global variable to avoid conflict with other programmes sharing the environment.

7 7 Example of Functions in Modular Arithmetic Remainder & Modular Functions >> mod(38,3) ans = 2 >> rem(38,3) ans = 2 >> rem(38,-3) % rem (x,y) has the same sign as x (36/3) ans = 2 >> mod(38,-3) %mod(x,y) has the same sign as y (39/3) ans = -1 > which mod C:\matlab12\toolbox\matlab\elfun\mod.m

8 8 Creating Function M-files Must start with a function declaration in first line Function output=my_function(x) % suppose we want to create a function to calculate sine square. Enter the following in a new m-file and save the file as sin_square.m function x=sin_square(y) x=sin(y)*sin(y) >> which sin_square %function exist? >> type sin_square %type to screen if needed >> sin_square(pi/8) %use function >> u=sin_square(pi/8) u = 0.1464

9 9 Application Example: Determine Triangle Area There are different methods to calculate the area of a triangle depending on known parameters The Huron formula (Greek 1 st century) can be used if the sides of the triangle are known where s= semiperimeter Area=area of  ABC

10 10 Example on Function with More Variables % Calculates Area of a Triangle % Huron Formula :Input 3 sides % Usage: triangle_area(a,b,c) % area=triangle_area(a,b,c) % Example:- % triangle_area(3,4,5) % Area=triangle_area(6,8,10) function x=triangle_area(a,b,c) s=1/2*(a+b+c); x=sqrt(s*(s-a)*(s-b)*(s-c)); You can get help by >>help triangle_area % print comments after the function declaration

11 11 In-line Functions Use when a simple function is needed for many times within a programme Reside in the same programme file Name=inline(‘expression’,’arg1’,’arg2’…) Create an inline object based on character string Example: >> sin2_cos2=inline('sin(x)^2+cos(y)^2','x','y') sin2_cos2 = Inline function: sin2_cos2(x,y) = sin(x)^2+cos(y)^2 >> which sin2_cos2 sin2_cos2 is a variable. >> u=sin2_cos2(pi/2,pi/2) u = 1

12 12 Anonymous Function & Function Handle User can define a function at the command line or in M- file using a file handle without an associated file. It is available after MatLab v.6.  A function handle is a data type in MatLab containing all the information for referencing a function.  Created by using the @ operator or the str2func function Syntax:- handle = @(arglist)anonymous_function  For example, to create a square anonymous function, y = x 2 >> y=@(x)x^2; >> y(4) ans = 16

13 13 Example of Two Variables Anonymous Function g=@(x,y) (x.^2 + y.^2); ezsurf(g); shading flat; title('f(x,y)=x^2+y^2'); Use function handle to pass function into function for new applications as it is more efficient than string operations. Use inline function if MatLab flags an error.

14 14 Flow Control There are 4 flow control statements in MatLab If statement Switch statement While loops For loops The if statement and the while loops use relational or logical operation to determine programme flow

15 15 Loops For loop  Use when the number of passes are known ahead of time While loop  Use when the loop must terminate when a specific condition is met. Automatic indentation is available on the editor/debugger when pressing the enter key until an end statement is reached.

16 16 Relational Operators Meaning <Less than <=Less than or equal >Greater than >=Greater than or equal ==Equal to ~=Not equal to

17 17 Example on Relational Operator Example 1: a=[1 2 4 6 2]; b=[2 1 4 5 2]; a== b % check if a equals b a>b % check if a greater than b Example 2: x=1:5; y=4; % y is a scaler x<y % ans is a vector ans = 1 1 1 0 0 For a comparison to be true for an entire matrix, every element must be true(i.e. all equals to 1).

18 18 Find find searches a matrix and identifies which elements in that matrix meet certain criterion. >> x =[7 14 21 28 35] >> find(x>20) % get index of element ans = 3 4 5 >> z=find(x>21) % save indices into z z = 4 5

19 19 Example on using find % ex_find1 % Given a matrix x, find & print all elements with x>50. % x=[20 30 40;89 9 88;33 90 54]; disp('Given a matrix x=') disp(x) element=find(x>50); [row,col]=find(x>50); disp('Element in matrix x with value greater than 50 are as follows:-') fprintf('x(%d,%d)=%d\n',[row,col,x(element)]')

20 20 Logical Operators Logical OperatorMeaning ~Not &And |Or XorExclusive or Logical operator works element-wise on matrices Boolean operation: 1=true and 0=false

21 21 Truth Table InputNotAndOrXor xy~xx&yx|yxor(x,y) 001000 011011 100011 110110

22 22 The if & if/else Structure The if statement evaluates a logical expression and executes a group of statement when the expression is true If condition Statements End The if/else allows user to execute a series of statement if a condition is true and to skip to the else if the condition is false.  Example:- x=input('x=') if x>0 y=log(x) else disp('input must be positive') end

23 23 The elseif Structure The elseif structure allows user to check multiple criteria while keeping the code easy to read. For example:- If age<11 disp(‘You cannot get any ID card’) elseif age<17 disp(‘You may have a children ID card’) else age>21 disp(‘You may have a adult ID card’) End In this example, the programme steps thru the structure until it find a true statement, execute & exit or until it encounters the else

24 24 Example on Function with Logic Control % Calculates Area of a Triangle % Huron Formula :Input 3 sides % Usage: triangle_area(a,b,c) % area=triangle_area(a,b,c) % Example:- % triangle_area(3,4,5) % Area=triangle_area(6,8,10) function x=triangle_area(a,b,c) if a<0|b<0|c<0 error('Input a,b,c must be positive') elseif (a+b)<c|(a+c)<b|(b+c)<a warning('The sum of any two sides must be greater than the third side') else s=1/2*(a+b+c); x=sqrt(s*(s-a)*(s-b)*(s-c)); End % Save as triangle_area1.m and try (a,b,c) = (1,1,2.1)

25 25 Array Indexing - Use an Array as an Index to an Array MATLAB supports a type of array indexing that uses one array as the index into another array. Example:- Array B indexes into elements 1, 3, 6, 7, and 10 of array A. A = 5:5:50 A = 5 10 15 20 25 30 35 40 45 50 B = [1 3 6 7 10]; A(B) % syntax of Array Indexing ans = 5 15 30 35 50 Hence, the numeric values of array B designate the intended elements of A.

26 26 Array Indexing – Logical Indexing A Simple Example on logic operations:- >> q=1; r=2; >> q>r >> q<r We can use this logic operation in matrix for element selection. Logical indexing designates array elements of a matrix based on their position in an indexing array. This is a logical masking operation. True element in the indexing array is being used as a positional index.

27 27 Example on Logical Indexing Example:- Eliminate elements for A>0.5.  Creates logical array B that satisfies the condition A > 0.5, and uses the positions of ones in B to index A. This is known as logical indexing: Steps:- A = rand(3) B = A > 0.5 % set elements of B to 1 if A(B) = 0 The following is a short-hand logical indexing expression:- A(A > 0.5) = 0 We can test if B is logical using islogic(B)

28 28 Debugger Environment is created when functions are invoked and returned; variables are generated, modified and destroyed. We can check the programme state using a debugger. Debugger in MatLab available in two interfaces; command line interface (CLI) and graphical user interface (GUI) Using the debugger typically involved the following:-  Set one or more breakpoints where the debugger will stop execution Breakpoint can be line number or a condition such as stop on error, warning, etc.  Execute the programme and when the programme stops, you can examine the environment and troubleshoot your programme

29 29 Example on the use of debugger

30 30 Debugging When MATLAB reaches a breakpoint, it enters debug mode. The prompt changes to a K>> and, on the PC, the debugger window becomes active. All MATLAB commands are allowed at the prompt. To resume M-file function execution, use DBCONT or DBSTEP. To exit from the debugger, use DBQUIT. For example: to clear and set breakpoint at line 8  dbstop in ex_sumprimes at 8  dbclear in ex_sumprimes at 8 Others: help debug

31 31 Hints on Exercise 6.3 Generate 4 spheres using sphere function from MatLab Cut the spheres Commands that you may needed:- >> sphere >> hold on >> colormap(winter) >> camlight >> lighting phong >> axis equal

32 32 Plottools, Property Editor & Inspector >> a=randn(1000,2);hist(a) >> propedit % or from Desktop Menu >> inspect % bring up inspector >> propertyeditor % see desktop menu


Download ppt "The Hong Kong Polytechnic University Industrial Centre 1 MatLAB Lesson 7 : M-file Programming I Edward Cheung Room W311g 2008."

Similar presentations


Ads by Google