Download - MatLAB Lesson 7 : M-file Programming I
![Page 1: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/1.jpg)
1
The Hong Kong Polytechnic UniversityIndustrial Centre
MatLABLesson 7 : M-file Programming I
Edward Cheung
email: [email protected]
Room W311g
2008
![Page 2: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/2.jpg)
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
• fileSet path or >> pathtool
![Page 3: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/3.jpg)
3
Example of Script File
%script M-file%This program shows how to create a script filestart_th=0;end_th=2*pi;th=start_th:.1:end_th;x=sin(th);y=cos(th);plot(x,y);axis equaltitle('Sine vs. Cosine','fontsize',18)xlabel('Sine','fontsize',16)ylabel('Cosine','fontsize',16)
![Page 4: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/4.jpg)
4
Example of Script File (cont.)
>> save file as script_test.m>> script_test % run script file
![Page 5: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/5.jpg)
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
• 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
![Page 6: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/6.jpg)
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.
![Page 7: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/7.jpg)
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 modC:\matlab12\toolbox\matlab\elfun\mod.m
![Page 8: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/8.jpg)
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.mfunction 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
![Page 9: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/9.jpg)
9
Application Example: Determine Triangle Area
)(For
))()((
)(2
1
bac
csbsassArea
cbas
• 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
![Page 10: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/10.jpg)
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
![Page 11: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/11.jpg)
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_cos2sin2_cos2 is a variable.>> u=sin2_cos2(pi/2,pi/2)u = 1
![Page 12: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/12.jpg)
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 = x2
>> y=@(x)x^2; >> y(4) ans = 16
![Page 13: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/13.jpg)
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');
-5
0
5
-5
0
5
0
20
40
60
80
x
f(x,y)=x2+y2
y
• 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.
![Page 14: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/14.jpg)
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
![Page 15: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/15.jpg)
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.
![Page 16: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/16.jpg)
16
Relational Operators
Relational Operators Meaning
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal to
~= Not equal to
![Page 17: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/17.jpg)
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 ba>b % check if a greater than b
Example 2:x=1:5;y=4; % y is a scaler x<y % ans is a vectorans = 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).
![Page 18: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/18.jpg)
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 elementans = 3 4 5>> z=find(x>21) % save indices into zz = 4 5
![Page 19: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/19.jpg)
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)]')
![Page 20: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/20.jpg)
20
Logical Operators
Logical Operator Meaning
~ Not
& And
| Or
Xor Exclusive or
•Logical operator works element-wise on matrices
•Boolean operation: 1=true and 0=false
![Page 21: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/21.jpg)
21
Truth Table
Input Not And Or Xor
x y ~x x&y x|y xor(x,y)
0 0 1 0 0 0
0 1 1 0 1 1
1 0 0 0 1 1
1 1 0 1 1 0
![Page 22: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/22.jpg)
22
The if & if/else Structure
• The if statement evaluates a logical expression and executes a group of statement when the expression is trueIf condition
StatementsEnd
• 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
![Page 23: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/23.jpg)
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
![Page 24: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/24.jpg)
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)
![Page 25: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/25.jpg)
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:50A = 5 10 15 20 25 30 35 40 45 50
B = [1 3 6 7 10];
A(B) % syntax of Array Indexingans = 5 15 30 35 50
Hence, the numeric values of array B designate the intended elements of A.
![Page 26: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/26.jpg)
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.
![Page 27: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/27.jpg)
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 ifA(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)
![Page 28: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/28.jpg)
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
![Page 29: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/29.jpg)
29
Example on the use of debugger
![Page 30: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/30.jpg)
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
![Page 31: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/31.jpg)
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
220
20
20 rzzyyxx
![Page 32: MatLAB Lesson 7 : M-file Programming I](https://reader037.vdocuments.site/reader037/viewer/2022102809/56813c6b550346895da5fb5d/html5/thumbnails/32.jpg)
32
Plottools, Property Editor & Inspector
>> a=randn(1000,2);hist(a)>> propedit % or from Desktop Menu>> inspect % bring up inspector>> propertyeditor % see desktop menu