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

Slides:



Advertisements
Similar presentations
Why care about debugging? How many of you have written a program that worked perfectly the first time? No one (including me!) writes a program that works.
Advertisements

Flow Charts, Loop Structures
Programming with MATLAB
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
General Computer Science for Engineers CISC 106 Lecture 21 Dr. John Cavazos Computer and Information Sciences 04/10/2009.
Example – calculating interest until the amount doubles using a for loop: will calculate up to 1000 years, if necessary if condition decides when to terminate.
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Introduction to MATLAB MECH 300H Spring Starting of MATLAB.
Week 7 - Programming II Today – more features: – Loop control – Extending if/else – Nesting of loops Debugging tools Textbook chapter 7, pages
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
1 Chapter 9 Writing, Testing, and Debugging Access Applications.
Introduction to Matlab 1. Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators Plotting Flow Control Using of M-File Writing.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Introduction to MATLAB. Windows in MATLAB Command Window – where you enter data, run MATLAB code, and display results Command History - displays a log.
CISC474 - JavaScript 03/02/2011. Some Background… Great JavaScript Guides: –
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 6.
How to think through your program [ principles of good program design ] Rachel Denison MATLAB for Cognitive Neuroscience ICN, 13 December 2007.
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Matlab Programming, part 1 M-files It is generally more convenient to program in Matlab using m-files, ascii text files containing a set of Matlab commands.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
ENGR 1320 Final Review - Programming Major Topics: – Functions and Scripts – Vector and Matrix Operations in Matlab Dot product Cross product – Plotting.
Introduction to Engineering MATLAB – 6 Script Files - 1 Agenda Script files.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Flow of Control Part 1: Selection
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
Flow Control and Functions ● Script files ● If's and For's ● Basics of writing functions ● Checking input arguments ● Variable input arguments ● Output.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Matlab for Engineers Logical Functions and Control Structures Chapter 8.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
CSE123 Lecture 3 Files and File ManagementScripts.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Introduction to Matlab Part II 1Daniel Baur / Introduction to Matlab Part II Daniel Baur / Michael Sokolov ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften.
MATLAB Programming COMM2M Harry R. Erwin, PhD University of Sunderland.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
Debugging tools in Flash CIS 126. Debugging Flash provides several tools for testing ActionScript in your SWF files. –The Debugger, lets you find errors.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
1 Structured Programming EEN170 Programming in MATLAB.
EEE 161 Applied Electromagnetics
Matlab Training Session 4: Control, Flow and Functions
Python: Control Structures
Scripts & Functions Scripts and functions are contained in .m-files
Java Programming: Guided Learning with Early Objects
MATLAB DENC 2533 ECADD LAB 9.
Matlab Workshop 9/22/2018.
User Defined Functions
Introduction to MATLAB
StatLab Matlab Workshop
MATLAB Tutorial Dr. David W. Graham.
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Logical Operations In Matlab.
Presentation transcript:

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

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 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 Example of Script File (cont.) >> save file as script_test.m >> script_test % run script file

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 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 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 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 =

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 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 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 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 operator or the str2func function Syntax:- handle  For example, to create a square anonymous function, y = x 2 >> >> y(4) ans = 16

13 Example of Two Variables Anonymous Function (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 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 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 Relational Operators Meaning <Less than <=Less than or equal >Greater than >=Greater than or equal ==Equal to ~=Not equal to

17 Example on Relational Operator Example 1: a=[ ]; b=[ ]; 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 = For a comparison to be true for an entire matrix, every element must be true(i.e. all equals to 1).

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

19 Example on using find % ex_find1 % Given a matrix x, find & print all elements with x>50. % x=[ ; ; ]; 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 Logical Operators Logical OperatorMeaning ~Not &And |Or XorExclusive or Logical operator works element-wise on matrices Boolean operation: 1=true and 0=false

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

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 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 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 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 = B = [ ]; A(B) % syntax of Array Indexing ans = Hence, the numeric values of array B designate the intended elements of A.

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 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 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 Example on the use of debugger

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 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 Plottools, Property Editor & Inspector >> a=randn(1000,2);hist(a) >> propedit % or from Desktop Menu >> inspect % bring up inspector >> propertyeditor % see desktop menu