320 likes | 520 Views
MatLAB Lesson 7 : M-file Programming I. Edward Cheung email: icec@polyu.edu.hk Room W311g. 2008. Types of M-file. Script M-file doesn’t accept input argument No return output argument Operates on data in the workspace only
E N D
MatLABLesson 7 : M-file Programming I Edward Cheung email: icec@polyu.edu.hk Room W311g 2008
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 • fileSet path or >> pathtool
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)
Example of Script File (cont.) >> save file as script_test.m >> script_test % run script file
Functions • Types of functions • Built-in function • User-defined function • Function files are created and edited like script files using the editor/debugger window • fileNewM-file • First line must be the function’s definition • Syntax:- • function [output_arg]=fun_name (input_arg) • [] is not required for single output argument
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.
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
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
Application Example: Determine Triangle Area • There are different methods to calculate the area of a triangle depending on known parameters • The Huron formula (Greek 1st century) can be used if the sides of the triangle are known • where • s= semiperimeter • Area=area of ABC
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
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
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 = x2 >> y=@(x)x^2; >> y(4) ans = 16
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.
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
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.
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).
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
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)]')
Logical Operators • Logical operator works element-wise on matrices • Boolean operation: 1=true and 0=false
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
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
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)
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.
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.
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)
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
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
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
Plottools, Property Editor & Inspector >> a=randn(1000,2);hist(a) >> propedit % or from Desktop Menu >> inspect % bring up inspector >> propertyeditor % see desktop menu