1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221
|
|
- Randolph Whitehead
- 6 years ago
- Views:
Transcription
1 1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221
2 Functions Recall that an algorithm is a feasible solution to the specific problem. 1 A function is a piece of computer code that accepts an input argument from the caller and returns output for the specific job the caller dealing with. So, the function is a real solution. Functions allow you to modularize a program by separating its tasks into self-contained units. We can program more efficiently and avoid rewriting the computer code for calculations that are performed frequently. Write down the algorithm first, and then program for it. 1 A problem would be solved by couples of methods. Zheng-Liang Lu 170 / 221
3 Built-in Arithmetic Functions Zheng-Liang Lu 171 / 221
4 Built-in Rounding Functions Zheng-Liang Lu 172 / 221
5 Built-in Discrete Math Functions Zheng-Liang Lu 173 / 221
6 Built-in Max Functions Zheng-Liang Lu 174 / 221
7 Built-in Max Functions (Cont d) There are also min functions to find the minimal elements in arrays, similar to max. Zheng-Liang Lu 175 / 221
8 Built-in Average Functions Zheng-Liang Lu 176 / 221
9 Built-in Size Functions Zheng-Liang Lu 177 / 221
10 Variance and Standard Deviation Zheng-Liang Lu 178 / 221
11 Random Number Generators Zheng-Liang Lu 179 / 221
12 Also, you may use randi(n, m, n) to produce an m-by-n random integer matrix ranging from 1 to N. These random number generators are used to produce a set of testing data for your programs Also widely used in Monte Carlo simulation 2 and random number generation algorithms of other distributions 3. 2 See Glasserman (2003). 3 See the acceptance-rejection method and Metropolis-Hastings algorithm. Zheng-Liang Lu 180 / 221
13 User-Defined Functions The syntax of a user-defined function is given by 1 function [output var] = function name(input var) 2 % comment section The output variables, if there exist, are enclosed in square brackets. The input variables, if there exist, must be enclosed with parentheses. function name should start with a letter, and be the same as the file name in which it is saved. Before this function can be used, it must be saved into the current folder 4. 4 If not, change the current folder or add to the path pool. Zheng-Liang Lu 181 / 221
14 Functions without Input and Output 1 function [] = star( ) % [] and () can be dropped. 2 theta = pi / 2 : 0.8 * pi : 4.8 * pi; 3 r = ones(1, 6); 4 polar(theta, r) % plot in polar coordinate Zheng-Liang Lu 182 / 221
15 Example: Addition of Two Numbers 1 function z = myadd(x, y) 2 % input: x,y (two numbers) 3 % output: z (sum of x and y) 4 z = x + y; Zheng-Liang Lu 183 / 221
16 Example: Mean of A Sequence 1 function y = mymean(x) 2 % input: x (array) 3 % output: y (mean) 4 5 sum = 0; 6 for i = 1 : length(x) 7 sum = myadd(sum, x(i)); % call myadd 8 end 9 y = sum / length(x); Zheng-Liang Lu 184 / 221
17 Numbers of Arguments nargin determines the number of input arguments in a function when executed. nargout determines the number of output arguments from a function when executed. varargin is a special word with two roles: varargin declares a function with any number of arguments. 5 The variable varargin itself is a cell array containing the optional arguments to the function. varargout is a special word similar to varargin but for outputs. 5 Note that varargin must be declared as the last input argument and collects all the inputs from that point onwards. Zheng-Liang Lu 185 / 221
18 Example Extend myadd to variable-input-length myadd. 1 function ret = myadd(varargin) 2 switch nargin 3 case 0 4 disp('no input.') 5 case 1 6 x = varargin{1}; 7 ret = x; 8 case 2 9 x = varargin{1}; 10 y = varargin{2}; 11 ret = x + y; 12 case 3 13 x = varargin{1}; 14 y = varargin{2}; 15 z = varargin{3}; Zheng-Liang Lu 186 / 221
19 16 ret = x + y + z; 17 otherwise 18 error('\ntoo many inputs.\n'); 19 end 20 end nargin, nargout, varargin and varargout provide a flexible design for user-defined functions. Note that the key word varargin and varargout should be the last item in the list. This mechanism is so-called function overloading. Zheng-Liang Lu 187 / 221
20 Scope of Variables The variables used in function m files are known as local variables. Any variable defined within the function exists only for the function to use. The only way a function can communicate between other functions is through input arguments and the outputs it returns. Unlike local variables, global variables are available to all parts of a computer program. Use global x to declare x as a global variable. In general, it is a bad idea to define global variables. 6 6 Recall the modularity. Zheng-Liang Lu 188 / 221
21 Example: Local Variables 1 function test 2 x = 0; 3 disp(x); 4 loop(x, 5); 5 disp(x); 6 end 7 8 function loop(x,n) 9 for i = 1 : n 10 x = x + 1; 11 disp(x); 12 end 13 end What are the numbers shown? How to return x in loop to test? Zheng-Liang Lu 189 / 221
22 Example: Global Variable 1 function test1(x) 2 global g 3 g=g+x; 4 disp(g) 5 test2(g) 6 end 7 8 function test2(y) 9 global g 10 g=g+y; 11 disp(g) 12 end Zheng-Liang Lu 190 / 221
23 1 clear all 2 clc 3 % main 4 global g 5 g=0; 6 disp(g) 7 test1(1); 1 >> What if you take global out of the function? Zheng-Liang Lu 191 / 221
24 Types of User-Defined Functions Primary functions and subfunctions Anonymous functions Nested functions Private functions Zheng-Liang Lu 192 / 221
25 Primary Functions and Subfunctions A function m-file may contain more than one user-defined function. The first defined function in the file is called the primary function, whose name is the same as the m-file name. All other functions in the file are called subfunctions. Subfunctions are normally visible only to the primary function and other subfunctions in the same file. Note that the order of the subfunctions does not matter, but function names must be unique within the m-file. Zheng-Liang Lu 193 / 221
26 Example 1 function [a c] = circle(r) % primary function 2 a = area(r); 3 c = circumference(r); 4 end 5 6 function y = area(x) % subfunction 1 7 y = pi*x.ˆ2; 8 end 9 10 function v = circumference(u) % subfunction 2 11 v = 2 * pi * u; 12 end Zheng-Liang Lu 194 / 221
27 1 >> [a c] = circle(2) 2 3 a = c = Note that if only one variable is assigned as output of the function, say, circle, then the area is returned while the circumference is dropped. Zheng-Liang Lu 195 / 221
28 Example 7 One subfunction can be called by other subfunctions in addition to the primary function. 1 function test1 2 fprintf('hi, there. This is test1.\n'); 3 test2; 4 end 5 6 function test2 7 fprintf('hi, there. This is test2.\n'); 8 test1; 9 end Notice that two subfunctions calling each other can lead to a loop, resulting a fatal crash. 7 Thanks to a lively class discussion (MATLAB-238) on June 14, Zheng-Liang Lu 196 / 221
29 Anonymous Functions Anonymous functions enable you to create a simple function without needing to create an m-file for it. Anonymous functions are defined by the function handle, denoted in the command window or in an m-file, and are available only until the workspace is cleared. For example, 1 >> f=@(x) x.ˆ2+x+1 % x.ˆ2 allows vectorization. 2 >> f([1 10]) 3 4 ans = Zheng-Liang Lu 197 / 221
30 You can pass the handle of an anonymous function to other functions. (Try.) You can create anonymous functions having more than one input. One anonymous function can call another to implement function composition. 1 >> f y) sqrt(x.ˆ 2 + y.ˆ 2); % f is a function... handle 2 >> g y) f(x, y).ˆ 2; % g is a composite function 3 >> g(3, 4) 4 5 ans = Zheng-Liang Lu 198 / 221
31 Exercise 89 1 function y = p(a, b, c) 2 y a * x.ˆ 2 + b * x + c; 3 end Note that the function p returns a function handle! 8 Thanks to a lively class discussion (MATLAB-244) on August 22, Contribution by Ms. Queenie Chang (MAT25108) on March 18, Zheng-Liang Lu 199 / 221
32 Nested Functions Functions are said to be nested if the functions are defined within the parent function. A nested function can access the variables of its parent function. 1 function f = parabola(a, b, c) 2 f %f is a function handle of p 3 function y = p(x) % p shares a, b, and c 4 y = a * x.ˆ2 + b * x + c; 5 end 6 end Zheng-Liang Lu 200 / 221
33 1 >> y = parabola(1, 2, 1); % that is y=xˆ2+2*x+1 2 >> y(5) 3 4 ans = Note that the nested functions are defined anywhere within the main function. (Why?) Zheng-Liang Lu 201 / 221
34 Private Functions Private functions are useful when you want to limit the scope of a function. A private functions resides in subfolder with the special name private. The private function is visible only to functions in the parent directory. Note that you cannot call the private function from the command line or from functions outside the parent of the private folder. Zheng-Liang Lu 202 / 221
35 Precedence When Calling Functions We can conduct the following experiment for this: 1 clear; clc; 2 % main 3 n = 10; 4 x = rand(1, n); 5 mu = mean(x); 6 sigma = std(x, mu); Zheng-Liang Lu 203 / 221
36 1 function y = mean(x) 2 fprintf('this is my mean.\n'); 3 y = sum(x) / length(x) 4 std(x,y); % invoking std function 5 function z = std(x,y) 6 fprintf('this is my 1st std (nested function).\n'); 7 z = sqrt(sum(x.ˆ 2) / length(x) - y ˆ 2) 8 end 9 end function z = std(x, y) 12 fprintf('this is my 2nd std (subfunction).\n'); 13 z = sqrt(sum(x.ˆ 2) / length(x) - y ˆ 2) 14 end Zheng-Liang Lu 204 / 221
37 1 function z = std(x, y) 2 fprintf('this is my 3rd std (local file).\n'); 3 z = sqrt(sum(x.ˆ 2) / length(x) - y ˆ 2) 4 end 1 function z = std(x,y) 2 fprintf('this is my 4th std (private).\n'); 3 z = sqrt(sum(x.ˆ 2) / length(x) - y ˆ 2) 4 end Zheng-Liang Lu 205 / 221
38 Precedence When Calling Functions (Concluded) 1 Nested functions 2 Subfunctions within the same file 3 Private functions 4 Local functions in the same directory 5 Built-in functions 6 Standard m files in PATH Zheng-Liang Lu 206 / 221
39 Calling Functions There are four common ways to invoke a function. As a character string identifying the appropriate function m-file. 1 function y = fun1(x) 2 y = x.ˆ2-4; % vectorized function 3 end 1 >> fun1([1 2 3]) 2 3 ans = As a function handle to an existing function M-file. Zheng-Liang Lu 207 / 221
40 1 >> 3) % returns the function value at ans = As a string expression. 1 >> fun2 = 'x.ˆ 2-4'; 2 >> x = fzero(fun2, [0, 3]); % find the root of fun1 in... [0,3] 3 4 x = Zheng-Liang Lu 208 / 221
41 As an inline function object. 1 >> fun inline = inline(fun2); 2 >> x = fzero(fun inline, [0, 3]) 3 4 x = The function handle method (method 2) is the fastest method, followed by method 1. In addition to speed improvement, another advantage of using a function handle is that it provides access to subfunctions, which are normally not visible outside of their m-file. Zheng-Liang Lu 209 / 221
42 Example: Bisection Method The bisection method in mathematics is a root-finding method that repeatedly bisects an interval and then selects a subinterval in which a root must lie for further processing. (Why?) It is often used to obtain an approximate solution. Zheng-Liang Lu 210 / 221
43 Zheng-Liang Lu 211 / 221
44 Idea of Bisection Method 1. At each step, the algorithm divides the interval in two by computing the midpoint c = (a + b)/2 of the interval and the value of the function f (c) at that point. 2. Unless c is itself a root (which is very unlikely, but possible), there are now two possibilities: either f (a) and f (c) have opposite signs and bracket a root, or f (c) and f (b) have opposite signs and bracket a root. Zheng-Liang Lu 212 / 221
45 3. The method selects the subinterval that is a bracket as a new interval to be used in the next step. 4. In this way the interval that contains a zero of f is reduced in width by 1 2 at each step. 5. The process is continued until the interval is sufficiently small How small? A certain number you give is to be the stop criteria. Zheng-Liang Lu 213 / 221
46 Problem Formulation Input - Target function f (x) - Endpoints of the interval [a, b] for any real numbers a < b - Minimal interval length ɛ int = b a Output - the approximate root ˆr Note that a and b will be updated iteratively. Zheng-Liang Lu 214 / 221
47 Solution 1 clear; clc; format long; 2 3 a = input('a =?\n'); 4 b = input('b =?\n'); 5 f x.ˆ 3 - x - 2; % target function 6 eps int = 1e-5; 7 iter = 0; % the number of iterations 8 9 if f(a) == 0 10 r = a; % lucky a 11 elseif f(b) == 0 12 r = b; % lucky b 13 else 14 while b - a > eps int 15 iter = iter + 1; 16 c = (a + b) / 2; % middle point 17 if f(c) == 0 Zheng-Liang Lu 215 / 221
48 18 r = c; % lucky c 19 break; 20 elseif (f(a)*f(c) < 0) 21 b = c; 22 elseif (f(b)*f(c) < 0) 23 a = c; 24 else 25 error('failure: f(a) * f(c) > 0 and f(c) *... f(b) > 0.'); 26 end 27 fprintf('%d: %f', iter, c); 28 end 29 r = c % approximate solution 30 end Zheng-Liang Lu 216 / 221
49 c = Zheng-Liang Lu 217 / 221
50 Remarks Time complexity: O(log 2 (n)) What is n? In this case, n = b a. (Why?) ɛ int So, it is an algorithm which runs in log time. This means that you need to make a trade-off between the numerical precision, that is, the number of digits, and the computation time. Be aware that this algorithm works well only with the premise that the behavior in [a, b] is mild. Approximate solutions may be significantly influenced by the initial interval [a, b]. 11 f (c) 0 but not equal to exactly 0. (Why?) 11 You may try another algorithm for the root finding problem, say, the Newton-Raphson method. Zheng-Liang Lu 218 / 221
51 Exercise Make your bisection method algorithm into a user-defined function, say, bisec. So, you can call bisec to find a root for a specific function in the command window or other programs. Besides, you should extend the function with more input arguments for parameters used in bisec. Zheng-Liang Lu 219 / 221
52 Problem Formulation Input - Target function f (x) - Endpoints of the interval [a, b] for any real numbers a < b - Minimal interval length ɛ int = b a Output - The approximate root ˆr Zheng-Liang Lu 220 / 221
53 1 function r=bisec(f,a,b,eps int,eps abs) >> bisec(@(x) x.ˆ 3 - x - 2, 0, 3, 1e-9, 1e-9) 2 3 ans = Zheng-Liang Lu 221 / 221
1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225
1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225 Functions The first thing of the design of algorithms is to divide and conquer. A large and complex problem would be solved by couples
More informationScope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable.
Scope of Variables The variables used in function m-files are known as local variables. Any variable defined within the function exists only for the function to use. The only way a function can communicate
More informationˆ Note that we often make a trade-off between time and space. ˆ Time complexity ˆ Space complexity. ˆ Unlike time, we can reuse memory.
ˆ We use O-notation to describe the asymptotic 1 upper bound of complexity of the algorithm. ˆ So O-notation is widely used to classify algorithms by how they respond to changes in its input size. 2 ˆ
More informationJump Statements. ˆ The break statement exits a for or while loop completely.
Jump Statements ˆ The break statement exits a for or while loop completely. ˆ No longer in the loop. ˆ Aka early termination. ˆ To skip the rest of the instructions in the loop and begin the next iteration,
More informationGlobal Variables. ˆ Unlike local variables, global variables are available to all functions involved.
Global Variables ˆ Unlike local variables, global variables are available to all functions involved. ˆ Use global to declare x as global. ˆ For example, the universal constant, say,. 1 ˆ However, it is
More informationExercise: Sorting 1. ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order).
Exercise: Sorting 1 ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order). ˆ For example, A = [5, 4, 1, 2, 3]. ˆ Then the sorted array is [1, 2, 3, 4, 5]. ˆ You
More informationArrays. ˆ An array, is a linear data structure consisting of a collection of elements, each identified by one array index. ˆ For math, arrays could be
Arrays ˆ An array, is a linear data structure consisting of a collection of elements, each identified by one array index. ˆ For math, arrays could be ˆ row vectors: u R 1 n for any positive integer n ˆ
More informationSECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB
SECTION 2: PROGRAMMING WITH MATLAB MAE 4020/5020 Numerical Methods with MATLAB 2 Functions and M Files M Files 3 Script file so called due to.m filename extension Contains a series of MATLAB commands The
More informationChapters 6-7. User-Defined Functions
Chapters 6-7 User-Defined Functions User-Defined Functions, Iteration, and Debugging Strategies Learning objectives: 1. Write simple program modules to implement single numerical methods and algorithms
More informationECE 102 Engineering Computation
ECE 102 Engineering Computation Phillip Wong MATLAB Function Files Nested Functions Subfunctions Inline Functions Anonymous Functions Function Files A basic function file contains one or more function
More informationSelections. Zheng-Liang Lu 91 / 120
Selections ˆ Selection enables us to write programs that make decisions on. ˆ Selection structures contain one or more of the if, else, and elseif statements. ˆ The end statement denotes the end of selection
More informationMATLAB TUTORIAL WORKSHEET
MATLAB TUTORIAL WORKSHEET What is MATLAB? Software package used for computation High-level programming language with easy to use interactive environment Access MATLAB at Tufts here: https://it.tufts.edu/sw-matlabstudent
More information10 M-File Programming
MATLAB Programming: A Quick Start Files that contain MATLAB language code are called M-files. M-files can be functions that accept arguments and produce output, or they can be scripts that execute a series
More informationChapter 3 Functions and Files
Chapter 3 Functions and Files Getting Help for Functions You can use the lookfor command to find functions that are relevant to your application. For example, type lookfor imaginary to get a list of the
More informationCommon Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141
Common Errors 2 double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Generating random numbers Example Write a program which generates
More informationVariables and Assignments
Variables and Assignments ˆ A variable is used to keep a value or values. ˆ A box which contains something. ˆ In most languages, a statement looks like var = expression, where var is a variable and expression
More informationMATLAB Lecture 4. Programming in MATLAB
MATLAB Lecture 4. Programming in MATLAB In this lecture we will see how to write scripts and functions. Scripts are sequences of MATLAB statements stored in a file. Using conditional statements (if-then-else)
More informationScientific Computing with MATLAB
Scientific Computing with MATLAB Dra. K.-Y. Daisy Fan Department of Computer Science Cornell University Ithaca, NY, USA UNAM IIM 2012 2 Focus on computing using MATLAB Computer Science Computational Science
More informationLECTURE 1. What Is Matlab? Matlab Windows. Help
LECTURE 1 What Is Matlab? Matlab ("MATrix LABoratory") is a software package (and accompanying programming language) that simplifies many operations in numerical methods, matrix manipulation/linear algebra,
More informationArithmetic Compound Assignment Operators
Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 141 Example 1... 2 int x = 1; 3 System.out.println(x);
More informationEL2310 Scientific Programming
(pronobis@kth.se) Overview Overview Wrap Up More on Scripts and Functions Basic Programming Lecture 2 Lecture 3 Lecture 4 Wrap Up Last time Loading data from file: load( filename ) Graphical input and
More informationReals 1. Floating-point numbers and their properties. Pitfalls of numeric computation. Horner's method. Bisection. Newton's method.
Reals 1 13 Reals Floating-point numbers and their properties. Pitfalls of numeric computation. Horner's method. Bisection. Newton's method. 13.1 Floating-point numbers Real numbers, those declared to be
More informationIntroduction to MATLAB 7 for Engineers
PowerPoint to accompany Introduction to MATLAB 7 for Engineers William J. Palm III Chapter 3 Functions and Files Copyright 2005. The McGraw-Hill Companies, Inc. Permission required for reproduction or
More informationIntroduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices
Introduction to Interactive Calculations Matlab is interactive, no need to declare variables >> 2+3*4/2 >> V = 50 >> V + 2 >> V Ans = 52 >> a=5e-3; b=1; a+b Most elementary functions and constants are
More informationLogic is the anatomy of thought. John Locke ( ) This sentence is false.
Logic is the anatomy of thought. John Locke (1632 1704) This sentence is false. I know that I know nothing. anonymous Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than
More informationUser Defined Functions
User Defined Functions 120 90 1 0.8 60 Chapter 6 150 0.6 0.4 30 0.2 180 0 210 330 240 270 300 Objectives Create and use MATLAB functions with both single and multiple inputs and outputs Learn how to store
More informationMATH2070: LAB 3: Roots of Equations
MATH2070: LAB 3: Roots of Equations 1 Introduction Introduction Exercise 1 A Sample Problem Exercise 2 The Bisection Idea Exercise 3 Programming Bisection Exercise 4 Variable Function Names Exercise 5
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 88 / 133 Flow Controls The basic algorithm (and program) is constituted
More informationMBI REU Matlab Tutorial
MBI REU Matlab Tutorial Lecturer: Reginald L. McGee II, Ph.D. June 8, 2017 MATLAB MATrix LABoratory MATLAB is a tool for numerical computation and visualization which allows Real & Complex Arithmetics
More informationThe return Statement
The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return
More informationMATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks
MATLAB Basics Stanley Liang, PhD York University Configure a MATLAB Package Get a MATLAB Student License on Matworks Visit MathWorks at https://www.mathworks.com/ It is recommended signing up with a student
More informationIntroduction to MATLAB for Engineers, Third Edition
PowerPoint to accompany Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 3 Functions and Files Copyright 2010. The McGraw-Hill Companies, Inc. 3-2 Getting Help for Functions
More informationAn interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.
Using Monte Carlo to Estimate π using Buffon s Needle Problem An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Here s the problem (in a simplified form). Suppose
More informationSTATISTICS 579 R Tutorial: More on Writing Functions
Fall 2005 1. Iterative Methods: STATISTICS 579 R Tutorial: More on Writing Functions Three kinds of looping constructs in R: the for loop, the while loop, and the repeat loop were discussed previously.
More informationMATLAB - FUNCTIONS. Functions can accept more than one input arguments and may return more than one output arguments.
MATLAB - FUNCTIONS http://www.tutorialspoint.com/matlab/matlab_functions.htm Copyright tutorialspoint.com A function is a group of statements that together perform a task. In MATLAB, functions are defined
More information1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137
1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 89 / 137 Flow Controls The basic algorithm (and program) is constituted
More information1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199
1 class Lecture5 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 Methods 2 Methods can be used to define reusable code, and organize
More informationExample: Monte Carlo Simulation 1
Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149
More informationEL2310 Scientific Programming
Lecture 4: Programming in Matlab Yasemin Bekiroglu (yaseminb@kth.se) Florian Pokorny(fpokorny@kth.se) Overview Overview Lecture 4: Programming in Matlab Wrap Up More on Scripts and Functions Wrap Up Last
More informationELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)
Introduction ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah) MATLAB is a powerful mathematical language that is used in most engineering companies today. Its strength lies
More informationSketchpad Graphics Language Reference Manual. Zhongyu Wang, zw2259 Yichen Liu, yl2904 Yan Peng, yp2321
Sketchpad Graphics Language Reference Manual Zhongyu Wang, zw2259 Yichen Liu, yl2904 Yan Peng, yp2321 October 20, 2013 1. Introduction This manual provides reference information for using the SKL (Sketchpad
More informationOutline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.
CSE 170 Interacting with MATLAB Instructor: Aijun An Department of Computer Science and Engineering York University aan@cse.yorku.ca Outline Starting MATLAB MATLAB Windows Using the Command Window Some
More informationLecture 4: Complex Numbers Functions, and Data Input
Lecture 4: Complex Numbers Functions, and Data Input Dr. Mohammed Hawa Electrical Engineering Department University of Jordan EE201: Computer Applications. See Textbook Chapter 3. What is a Function? A
More informationMethod Invocation. Zheng-Liang Lu Java Programming 189 / 226
Method Invocation Note that the input parameters are sort of variables declared within the method as placeholders. When calling the method, one needs to provide arguments, which must match the parameters
More information7 Control Structures, Logical Statements
7 Control Structures, Logical Statements 7.1 Logical Statements 1. Logical (true or false) statements comparing scalars or matrices can be evaluated in MATLAB. Two matrices of the same size may be compared,
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationLecture 6 MATLAB programming (4) Dr.Qi Ying
Lecture 6 MATLAB programming (4) Dr.Qi Ying Objectives User-defined Functions Anonymous Functions Function name as an input argument Subfunctions and nested functions Arguments persistent variable Anonymous
More informationswitch-case Statements
switch-case Statements A switch-case structure takes actions depending on the target variable. 2 switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: 7. 8. 9 case vk: 10 // statements 11 break;
More informationOutline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An
CSE 170 Interacting with MATLAB Instructor: Aijun An Department of Computer Science and Engineering York University aan@cse.yorku.ca Outline Starting MATLAB MATLAB Windows Using the Command Window Some
More informationMatlab and Octave: Quick Introduction and Examples 1 Basics
Matlab and Octave: Quick Introduction and Examples 1 Basics 1.1 Syntax and m-files There is a shell where commands can be written in. All commands must either be built-in commands, functions, names of
More informationBasic MATLAB Tutorial
Basic MATLAB Tutorial http://www1gantepedutr/~bingul/ep375 http://wwwmathworkscom/products/matlab This is a basic tutorial for the Matlab program which is a high-performance language for technical computing
More informationOutline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.
CSE 10 Interacting with MATLAB Instructor: Aijun An Department of Computer Science and Engineering York University aan@cse.yorku.ca Outline Starting MATLAB MATLAB Windows Using the Command Window Some
More informationFlow Control and Functions
Flow Control and Functions Script files If's and For's Basics of writing functions Checking input arguments Variable input arguments Output arguments Documenting functions Profiling and Debugging Introduction
More informationGetting started with MATLAB
Sapienza University of Rome Department of economics and law Advanced Monetary Theory and Policy EPOS 2013/14 Getting started with MATLAB Giovanni Di Bartolomeo giovanni.dibartolomeo@uniroma1.it Outline
More informationLecture 1: Hello, MATLAB!
Lecture 1: Hello, MATLAB! Math 98, Spring 2018 Math 98, Spring 2018 Lecture 1: Hello, MATLAB! 1 / 21 Syllabus Instructor: Eric Hallman Class Website: https://math.berkeley.edu/~ehallman/98-fa18/ Login:!cmfmath98
More informationIntroduction to Matlab. By: Dr. Maher O. EL-Ghossain
Introduction to Matlab By: Dr. Maher O. EL-Ghossain Outline: q What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display Facilities Flow Control
More informationChapter 3: Programming with MATLAB
Chapter 3: Programming with MATLAB Choi Hae Jin Chapter Objectives q Learning how to create well-documented M-files in the edit window and invoke them from the command window. q Understanding how script
More informationFUNCTIONS ( WEEK 5 ) DR. USMAN ULLAH SHEIKH DR. MUSA MOHD MOKJI DR. MICHAEL TAN LONG PENG DR. AMIRJAN NAWABJAN DR. MOHD ADIB SARIJARI
FUNCTIONS SKEE1022 SCIENTIFIC PROGRAMMING ( WEEK 5 ) DR. USMAN ULLAH SHEIKH DR. MUSA MOHD MOKJI DR. MICHAEL TAN LONG PENG DR. AMIRJAN NAWABJAN DR. MOHD ADIB SARIJARI OBJECTIVES Create Function 1) Create
More informationQuestion Points Score Total 100
Name Signature General instructions: You may not ask questions during the test. If you believe that there is something wrong with a question, write down what you think the question is trying to ask and
More informationStructure Array 1 / 50
Structure Array A structure array is a data type that groups related data using data containers called fields. Each field can contain any type of data. Access data in a structure using dot notation of
More informationExample. Write a program which generates 2 random integers and asks the user to answer the math expression.
Generating random numbers Example Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then
More informationAssignment #2: False Position Method
University of Puerto Rico Mayaguez Campus Department of Electrical & Computer Engineering Assignment #2: False Position Method Osvaldo M. Cardona 841-08-0990 Diana Rivera Negrón 802-08-6908 Ricardo I.
More informationExample. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.
Example Generating random numbers Write a program which generates 2 random integers and asks the user to answer the math expression. For example, the program shows 2 + 5 =? If the user answers 7, then
More informationDesktop Command window
Chapter 1 Matlab Overview EGR1302 Desktop Command window Current Directory window Tb Tabs to toggle between Current Directory & Workspace Windows Command History window 1 Desktop Default appearance Command
More informationGetting Started with Matlab
Chapter Getting Started with Matlab The computational examples and exercises in this book have been computed using Matlab, which is an interactive system designed specifically for scientific computation
More informationMAT 275 Laboratory 1 Introduction to MATLAB
MATLAB sessions: Laboratory 1 1 MAT 275 Laboratory 1 Introduction to MATLAB MATLAB is a computer software commonly used in both education and industry to solve a wide range of problems. This Laboratory
More informationConstraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial
1 Matlab Tutorial 2 Lecture Learning Objectives Each student should be able to: Describe the Matlab desktop Explain the basic use of Matlab variables Explain the basic use of Matlab scripts Explain the
More information21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie
21-Loops Part 2 text: Chapter 6.4-6.6 ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie While Loop Infinite Loops Break and Continue Overview Dr. Henry Louie 2 WHILE Loop Used to
More informationJava Methods. Lecture 8 COP 3252 Summer May 23, 2017
Java Methods Lecture 8 COP 3252 Summer 2017 May 23, 2017 Java Methods In Java, the word method refers to the same kind of thing that the word function is used for in other languages. Specifically, a method
More informationINTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD. July 2018
INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS DEPARTMENT Deniz Savas & Mike Griffiths July 2018 Outline MATLAB Scripts Relational Operations Program Control Statements Writing
More informationScanner Objects. Zheng-Liang Lu Java Programming 82 / 133
Scanner Objects It is not convenient to modify the source code and recompile it for a different radius. Reading from the console enables the program to receive an input from the user. A Scanner object
More informationMATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras
MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras Module No. #01 Lecture No. #1.1 Introduction to MATLAB programming
More informationIntroduction to MATLAB
Introduction to MATLAB The language of technical computing AM 581 Computational Laboratory Department of Applied Mechanics, IIT Madras MATLAB: technical computing language & interactive environment for
More informationf( x ), or a solution to the equation f( x) 0. You are already familiar with ways of solving
The Bisection Method and Newton s Method. If f( x ) a function, then a number r for which f( r) 0 is called a zero or a root of the function f( x ), or a solution to the equation f( x) 0. You are already
More informationIEEE Floating-Point Representation 1
IEEE Floating-Point Representation 1 x = ( 1) s M 2 E The sign s determines whether the number is negative (s = 1) or positive (s = 0). The significand M is a fractional binary number that ranges either
More informationPART 2 DEVELOPING M-FILES
PART 2 DEVELOPING M-FILES Presenter: Dr. Zalilah Sharer 2018 School of Chemical and Energy Engineering Universiti Teknologi Malaysia 17 September 2018 Topic Outcomes Week Topic Topic Outcomes 6-8 Creating
More informationMatlab for Engineers
Matlab for Engineers Alistair Johnson 31st May 2012 Centre for Doctoral Training in Healthcare Innovation Institute of Biomedical Engineering Department of Engineering Science University of Oxford Supported
More informationIntroduction. Like other programming languages, MATLAB has means for modifying the flow of a program
Flow control 1 Introduction Like other programming languages, MATLAB has means for modying the flow of a program All common constructs are implemented in MATLAB: for while then else switch try 2 FOR loops.
More informationWhat is MATLAB and howtostart it up?
MAT rix LABoratory What is MATLAB and howtostart it up? Object-oriented high-level interactive software package for scientific and engineering numerical computations Enables easy manipulation of matrix
More informationSPARK-PL: Introduction
Alexey Solovyev Abstract All basic elements of SPARK-PL are introduced. Table of Contents 1. Introduction to SPARK-PL... 1 2. Alphabet of SPARK-PL... 3 3. Types and variables... 3 4. SPARK-PL basic commands...
More informationfunction [s p] = sumprod (f, g)
Outline of the Lecture Introduction to M-function programming Matlab Programming Example Relational operators Logical Operators Matlab Flow control structures Introduction to M-function programming M-files:
More informationCloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,
Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;
More informationECE 202 LAB 3 ADVANCED MATLAB
Version 1.2 1 of 13 BEFORE YOU BEGIN PREREQUISITE LABS ECE 201 Labs EXPECTED KNOWLEDGE ECE 202 LAB 3 ADVANCED MATLAB Understanding of the Laplace transform and transfer functions EQUIPMENT Intel PC with
More informationRepetition Structures Chapter 9
Sum of the terms Repetition Structures Chapter 9 1 Value of the Alternating Harmonic Series 0.9 0.8 0.7 0.6 0.5 10 0 10 1 10 2 10 3 Number of terms Objectives After studying this chapter you should be
More informationWhat is a Function? EF102 - Spring, A&S Lecture 4 Matlab Functions
What is a Function? EF102 - Spring, 2002 A&S Lecture 4 Matlab Functions What is a M-file? Matlab Building Blocks Matlab commands Built-in commands (if, for, ) Built-in functions sin, cos, max, min Matlab
More informationMATLAB Second Seminar
MATLAB Second Seminar Previous lesson Last lesson We learnt how to: Interact with MATLAB in the MATLAB command window by typing commands at the command prompt. Define and use variables. Plot graphs It
More informationC Programming for Engineers Functions
C Programming for Engineers Functions ICEN 360 Spring 2017 Prof. Dola Saha 1 Introduction Real world problems are larger, more complex Top down approach Modularize divide and control Easier to track smaller
More informationIntroduction to Octave/Matlab. Deployment of Telecommunication Infrastructures
Introduction to Octave/Matlab Deployment of Telecommunication Infrastructures 1 What is Octave? Software for numerical computations and graphics Particularly designed for matrix computations Solving equations,
More informationCOMS 3101 Programming Languages: MATLAB. Lecture 2
COMS 3101 Programming Languages: MATLAB Lecture 2 Fall 2013 Instructor: Ilia Vovsha hbp://www.cs.columbia.edu/~vovsha/coms3101/matlab Lecture Outline Quick review of array manipulanon Control flow Simple
More informationFondamenti di Informatica
Fondamenti di Informatica Scripts and Functions: examples lesson 9 2012/04/16 Prof. Emiliano Casalicchio emiliano.casalicchio@uniroma2.it Agenda Examples Bisection method Locating roots Secant methods
More informationLAB: INTRODUCTION TO FUNCTIONS IN C++
LAB: INTRODUCTION TO FUNCTIONS IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2014 VERSION 4.0 PALMS MODULE 2 LAB: FUNCTIONS IN C++ 2 Introduction This lab will provide students with an
More informationINTRODUCTION TO NUMERICAL ANALYSIS
INTRODUCTION TO NUMERICAL ANALYSIS Cho, Hyoung Kyu Department of Nuclear Engineering Seoul National University 0. MATLAB USAGE 1. Background MATLAB MATrix LABoratory Mathematical computations, modeling
More informationC++ Programming Lecture 1 Software Engineering Group
C++ Programming Lecture 1 Software Engineering Group Philipp D. Schubert Contents 1. More on data types 2. Expressions 3. Const & Constexpr 4. Statements 5. Control flow 6. Recap More on datatypes: build-in
More informationAMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA
AMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA MATLAB (short for MATrix LABoratory) is a very useful piece of software for numerical
More informationCMAT Language - Language Reference Manual COMS 4115
CMAT Language - Language Reference Manual COMS 4115 Language Guru: Michael Berkowitz (meb2235) Project Manager: Frank Cabada (fc2452) System Architect: Marissa Ojeda (mgo2111) Tester: Daniel Rojas (dhr2119)
More informationIntroduction to MATLAB
Chapter 1 Introduction to MATLAB 1.1 Software Philosophy Matrix-based numeric computation MATrix LABoratory built-in support for standard matrix and vector operations High-level programming language Programming
More informationSECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing
SECTION 1: INTRODUCTION ENGR 112 Introduction to Engineering Computing 2 Course Overview What is Programming? 3 Programming The implementation of algorithms in a particular computer programming language
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationWhat is Matlab? The command line Variables Operators Functions
What is Matlab? The command line Variables Operators Functions Vectors Matrices Control Structures Programming in Matlab Graphics and Plotting A numerical computing environment Simple and effective programming
More informationIntroduction to MATLAB
to MATLAB Spring 2019 to MATLAB Spring 2019 1 / 39 The Basics What is MATLAB? MATLAB Short for Matrix Laboratory matrix data structures are at the heart of programming in MATLAB We will consider arrays
More information