Chapters 6-7. User-Defined Functions
|
|
- Silas Little
- 5 years ago
- Views:
Transcription
1 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 2. Test program output for accuracy using hand calculations and debugging techniques Topics/Outline: 1. Functions: purpose and definition 2. Examples 3. Pass by value and local memory 4. Debugging Chapter 6-7: User-Defined Functions 1
2 User-Defined Functions Good programs: Never type the same code twice Solutions: 1. Iteration structure (loops) 2. Put code you need to reuse in a function We already constructed several simple user-defined functions in Chapters 3 and 4 MATLAB Script File A collection of MATLAB statements (M-files) that are stored in a file Script file produces the same result as if all commands had been typed directly into the Command Window Script files share the Command Window s workspace All variables defined before the start of script file or created by the script file remain in the workspace A script file has no input arguments and returns no results, but can communicate with other script files through the data left behind in the workspace Chapter 6-7: User-Defined Functions 2
3 MATLAB Functions A special type of M-file that runs in its own independent workspace Receives input data through an input argument list Returns results to the call through output argument list A function may contain multiple input and multiple output arguments MATLAB Built-In Functions We already know how to use MATLAB built-in functions y = sqrt(x) output can have any name input can have any name function theta = atan2(y,x) single output function multiple inputs [max_a,index_a] = max(a) multiple outputs function single input Chapter 6-7: User-Defined Functions 3
4 User-Defined Functions One output variable function y = mname(input arguments) More than one output variables function [y1, y2, ] = mname(input arguments) Both functions and scripts are M-files Differences between scripts and functions Scripts share variables with the main workspace Functions do not User-Defined Functions Special.m-files The first executable line must be function [output1,output2, ] = mname (input1, input2, ) square brackets name of the.m-file parentheses The.m filename must be the same as the function name (including capitalization): mname.m May contain multiple input and multiple output arguments Input and output arguments can be any name The bracket can be dropped if only one output argument or only the first output is desired Chapter 6-7: User-Defined Functions 4
5 User-Defined Functions function [output1,output2, ] = mname (input1, input2, ) Examples: function y = my_func(x) y = x.^3 + 3*x.^2-5*x + 2; function [r,theta] = rect2polar(x,y) r = sqrt(x.^2 + y.^2); theta = 180/pi * atan2(y,x); function [x,y] = polar2rect(r,theta) x = r * cos(theta * pi/180); y = r * sin(theta * pi/180); User-Defined Function Example: equipment.m Prompt for interactive input Optional end Chapter 6-7: User-Defined Functions 5
6 User-Defined Function Example: equipment.m Prompt for input at Command Window >> equipment Current temperature in degree Fahrenheit: 130 Too hot - equipment malfunctioning. >> equipment Current temperature in degree Fahrenheit: 100 Normal operating range. >> equipment Current temperature in degree Fahrenheit: 78 Normal operating range. >> equipment Current temperature in degree Fahrenheit: 68 Temperature below desired operating range. >> equipment Current temperature in degree Fahrenheit: 45 Too Cold - turn off equipment User-Defined Function Example: equipment2.m One input argument, no output argument Chapter 6-7: User-Defined Functions 6
7 User-Defined Function Example: equipment2.m Specific temperature in the input argument >> equipment2(130) Too hot - equipment malfunctioning. >> equipment2(100) Normal operating range. >> equipment2(78) Normal operating range. >> equipment2(68) Temperature below desired operating range. >> equipment2(45) Too Cold - turn off equipment. Anything you wish to pass to the main program should be specified in the output argument list Example: average.m Create function average.m to evaluate the mean of any variable Try which mean in command window to open the MATLAB built-in mean.m file Type help mean and see the help block Construct a user-defined function average.m (avoid using mean.m) function [xbar] = average(x) Chapter 6-7: User-Defined Functions 7
8 Example: average.m Include a data dictionary for user-defined function Return the mean value xbar Example: average.m >> y = [ ]; >> [ym] = average(y) ym = >> ym = average(y) ym = bracket can be neglected if there is only one output or only the first output is desired >> who Your variables are: y ym >> mean(y) ans = local memory destroyed: (x,n,i,sumx,xbar) MATLAB built-in function Function average.m produces identical result as mean.m Chapter 6-7: User-Defined Functions 8
9 Example: average.m >> y = 1:0.2:12; >> [ysq_bar] = average(y.^2) User-defined function ysq_bar = >> mean(y.^2) ans = MATLAB built-in function Note: use square brackets for output, and parentheses for input MATLAB function receives VALUES, not VARIABLES Pass-by-Value MATLAB functions receive VALUES, not VARIABLES Values are passed to function through input (i.e., [ ], etc.) Variables (i.e., y, y.^2, etc.) are NOT Similar operations for output Local Memory: any variable created or modified inside a function is cleared (i.e., destroyed) when the function ends Chapter 6-7: User-Defined Functions 9
10 Pass-by-Value Scheme >> a = 2; b = [6 4]; >> fprintf('before sample: a = %f, b= %f %f\n',a,b); Before sample: a = , b = >> pass_by_value(a,b); In sample: a = , b = In sample: a = , b = >> fprintf('after sample: a = %f, b= %f %f\n',a,b); After sample: a = , b = Pass-by-Value Scheme >> a = 2; b = [6 4]; Before sample: a = , b= In sample: a = , b= In sample: a = , b= After sample: a = , b= (a,b) were changed from (2,[6,4]) to (10,[60,40]) inside the pass_by_value function But the original (a,b) values were restored after the completion of the function execution Function pass_by_value has no effect on the calling program Chapter 6-7: User-Defined Functions 10
11 Function Outputs Everything you want returned by a function must be listed as an output [output1, output2, ] = function(input1, input2, ) If there is only one output, or only the first output is desired: [output1] = function(input1, input2, ) or output1 = function(input1, input2, ) If second output is desired, then it is necessary to list all outputs Function Debugging The variables inside function do not show in Workspace To view values as function executes: insert break point (in Editor Window) This allows MATLAB to temporarily convert function to program so all variables stay in Workspace Use Workspace to debug problems in function (select Debug tab in MATLAB desktop) Chapter 6-7: User-Defined Functions 11
12 Function Debugging Use average.m as an example Step through index i Set breakpoint Function Debugging Set breakpoint and step through index i You may set multiple breakpoints Click Step (or press F10) to step through the code one line at a time Chapter 6-7: User-Defined Functions 12
13 Function Debugging Use continue in Debug tab to step through index i = 1, 2, K>> clear all K>> y = [ ]; K>> ym = average(y); 9 sumx = sumx + x(i); K>> i i = 1 K>> sumx sumx = 0 K>> i i = 2 K>> sumx sumx = 1 K>> i i = 3 K>> sumx sumx = -2 K>> i i = 4 K>> sumx sumx = 2 K>> i i = 5 K>> sumx sumx = 9 K>> who Your variables are: i n sumx x (Function variables stay in workspace) User-Defined Function Example Lab Assignment #1 (extract dates and prices) Chapter 6-7: User-Defined Functions 13
14 User-Defined Function Example Lab assignment #1 >> [year,month,supply] = mgsupply(mgs_vec); Year Month Production User-Defined Function Multiple inputs and multiple outputs: average_temperature.m Chapter 6-7: User-Defined Functions 14
15 User-Defined Function Multiple inputs and multiple outputs: average_temperature.m >> dates = [ ; ; ; ]; >> tps = [45.3; 55.8; 63.1; 39.5]; >> [year,month,date,tp,tp_avg] = average_temperature(dates,tps); Year Month Date Temperature Average temperature = Nested: call another user-defined function within a user-defined function function [xbar] = average(x) User-Defined Function Interactive inputs: average_temperature2.m Chapter 6-7: User-Defined Functions 15
16 User-Defined Function Interactive inputs: average_temperature2.m >> [year,month,date,tp,tp_avg] = average_temperature2; Enter selected dates in YYYYMMDD format = [ ; ; ; ] Enter daily temperature = [55.24; 78.50; 85.36; 38.71] Year Month Date Temperature Average temperature = Enter dates and daily temperatures directly at the command prompt Function: Evaluate CVEN 302 Grade Chapter 6-7: User-Defined Functions 16
17 User-Defined Function if elseif Structure >> cven302_grade Enter Student Name: Jane Doe Enter Student ID: Enter Homework Average (30%): 96 Enter Exam I score (20%): 88 Enter Exam II score (20%): 92 Enter Final Exam score (30%): 85 Your Semester Average is: Your Semester Grade is : A >> cven302_grade Enter Student Name: John Doe Enter Student ID: Enter Homework Average (30%): 62 Enter Exam I score (20%): 84 Enter Exam II score (20%): 80 Enter Final Exam score (30%): 91 Your Semester Average is: Your Semester Grade is : C Benefits of Functions Independent testing of sub-tasks (unit testing) Reusable code (e.g., average.m) Isolation from unintended side effects (local variables) We will program most of the numerical methods learned as reusable functions e.g., Once you have a linear regression module, you may apply it to any dataset Chapter 6-7: User-Defined Functions 17
18 Optional Arguments Functions can be more flexible if we let the users decide the number of input and output arguments How does MATLAB decide what to do with different number of input arguments? >> A = zeros(10); >> A = zeros(10,4); >> A = zeros(10,4,3); >> help zeros ZEROS Zeros array. ZEROS(N) is an N-by-N matrix of zeros. ZEROS(M,N) or ZEROS([M,N]) is an M-by-N matrix of zeros. ZEROS(M,N,P,...) or ZEROS([M N P...]) is an M-by-N-by-P-by-... array of zeros. ZEROS(SIZE(A)) is the same size as A and all zeros. ZEROS with no arguments is the scalar 0. ZEROS(M,N,...,CLASSNAME) or ZEROS([M,N,...],CLASSNAME) is an M-by-N-by-... array of zeros of class CLASSNAME. Note: The size inputs M, N, and P... should be nonnegative integers. Negative integers are treated as 0. Optional Output Arguments >> A = zeros(10,4,3); >> size(a) ans = >> size(a,1) ans = 10 >> size(a,2) ans = 4 >> size(a,3) ans = 3 >> m = size(a) m = >> A = zeros(10,4,3); >> [m,n] = size(a) m = 10 n = 12 >> [m,n,p] = size(a) m = 10 n = 4 p = 3 >> [m,n,p,q] = size(a) m = 10 n = 4 p = 3 q = 1 The answer depends on the number (0-4) of output arguments Chapter 6-7: User-Defined Functions 18
19 Optional Input Arguments We may call the built-in function plot with as few as two elements or as many as seven input arguments How does MATLAB decide what to do with optional arguments? (Color/symbol/line type, LineWidth, MarkerSize, MarkerEdgeColor, MarkerFaceColor) Optional Input Arguments Customize plot using optional arguments: Color/symbol/line type, LineWidth, MarkerSize, MarkerEdgeColor, MarkerFaceColor Chapter 6-7: User-Defined Functions 19
20 Special Functions for Functions Use the following six special functions to get information about optional arguments and to report errors in those arguments nargin nargout nargchk error return the number of actual input arguments used to call the function return the number of actual output arguments used to call the function return error if the function is called with too few or too many arguments display error message and abort the function execution. Used for fatal errors. warning display warning message and continue function execution. Used for non-fatal errors. inputname returns the actual name of the variable that corresponds to a particular function number Optional Arguments [output1,output2] = size(input1) if nargin == 1 if nargout == 1 statements elseif nargout == 2 another statements else error( too many output arguments ) end another statements end Chapter 6-7: User-Defined Functions 20
21 Optional Arguments: animal_population.m Optional Arguments: animal_population.m inputname, nargchk, nargin, error, warning >> dog = 23; cat = 15; rabbit = 57; pig = 46; tiger = 1; mouse = 0; >> animal_population;??? Error using ==> animal_population at 5 Not enough input arguments. >> animal_population(dog); The first argument is named "dog". Total animal population = 23 nargin = 0 nargin = 1 >> animal_population(dog,rabbit); The first argument is named "dog". The second argument is named "rabbit". Total animal population = 80 >> animal_population(rabbit,cat,dog); The first argument is named "rabbit". The second argument is named "cat". The third argument is named "dog". Total animal population = 95 nargin = 2 nargin = 3 Chapter 6-7: User-Defined Functions 21
22 Optional Arguments: animal_population.m inputname, nargchk, nargin, error, warning >> dog = 23; cat = 15; rabbit = 70; pig = 46; tiger = 1; mouse = 0; >> animal_population(dog,cat,mouse,pig); The first argument is named "dog". The second argument is named "cat". The third argument is named "mouse". nargin = 4 Warning: Zero or negative animal population > In animal_population at 20 The fourth argument is named "pig". Total animal population = 84 >> animal_population(cat,dog,tiger,rabbit); The first argument is named "cat". The second argument is named "dog". The third argument is named "tiger". The fourth argument is named "rabbit". Total animal population = 109 nargin = 4 >> animal_population(dog,cat,tiger,rabbit,pig);??? Error using ==> animal_population Too many input arguments. nargin = 5 Global Memory Sharing data using global memory, accessible from any workspace Makes values in global variables available and modifiable by all functions and programs If necessary, make global variables ALL CAPS and avoid modifying them in functions global GRAVITY, VAR2, VAR3 GRAVITY = function [ ] = fname( ) global GRAVITY, VAR2, VAR3 weight = mass * GRAVITY; end Chapter 6-7: User-Defined Functions 22
23 Persistent Memory Preserving data between calls to a function Memory in functions is LOCAL, and is destroyed when function ends Sometimes you need a function to remember a value, such as how many times it has been called If such a counter were destroyed every time the function exited, the count would never exceed 1 Declare these variables: persistent var1 var2 var3 persistent n % number of input values persistent sum_x % running sum of values persistent sum_x2 % running sum of values squared Function Functions Functions whose input argument include the names of other functions (used during function s execution) Passing functions to functions What if the input to a function needs to be a function name? Example: want a built-in MATLAB function to do something with a user-defined function >> root = fzero('cos',[0 pi]) root = >> x = 0:0.1:10; >> y = feval(inline('sin(x)+exp(-x)'),x); We will use inline function and feval later when testing various numerical methods Chapter 6-7: User-Defined Functions 23
24 Subfunctions You may put more than one function in a.m file Subfunctions are only available when the main function is used. File mystates.m mystats Function mystats is accessible from outside the file mean_udf median_udf Functions mean_udf and median_udf are only accessible from inside the file Subfunctions Subfunctions mean_udf & median_udf are only accessible from inside the file mystats.m Chapter 6-7: User-Defined Functions 24
25 Private Functions Functions that reside in subdirectories with the special name private They are only visible to other functions in the private directory or to functions in the parent directory Private functions are restricted to the private directory and to the parent directory that contains it Since private functions are invisible outside of the parent directory, the same function names can be used in other directories Nested Functions Defined entirely within the body of the host function Visible only to the host function and the other nested functions embedded at the same level within the same host function host_function nested_function_1 end % nested_function_1 nested_function_2 end % nested_function_2 end % host_function Variables defined in host function are visible inside any nested functions Variables defined within nested functions are not visible in the host functions nested_function_1 can be called by host_function or nested_function_2 nested_function_2 can be called by host_function or nested_function_1 Chapter 6-7: User-Defined Functions 25
26 Order of Function Evaluation MATLAB locates functions in the following order: 1. Nested function with the specified name 2. Subfunction with the specified name 3. Private function with the specified name 4. Function in the current directory with the specified name 5. The first function found within the specified name of the MATLAB path Top-Down Program Design State the problem clearly Describe input and desired output, and any equations needed Work a hand-calculation Develop an algorithm to solve the problem Code the algorithm Test code against hand-calculation results Work on optimizations for speed Finalize comments and documentation Chapter 6-7: User-Defined Functions 26
27 Code Optimization Identify modules (functions) and separate them from the programs Keep program/functions as short as possible (split into smaller modules if possible) Write for clarity Look for orange hints in text editor Use built-in function if it exist Vectorize array operations Remove unnecessary debbuging calculations Chapter 6-7: User-Defined Functions 27
Chapter 6 User-Defined Functions. dr.dcd.h CS 101 /SJC 5th Edition 1
Chapter 6 User-Defined Functions dr.dcd.h CS 101 /SJC 5th Edition 1 MATLAB Functions M-files are collections of MATLAB statements that stored in a file, called a script file. Script files share the command
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 informationAMS 27L LAB #2 Winter 2009
AMS 27L LAB #2 Winter 2009 Plots and Matrix Algebra in MATLAB Objectives: 1. To practice basic display methods 2. To learn how to program loops 3. To learn how to write m-files 1 Vectors Matlab handles
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 information1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221
1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221 Functions Recall that an algorithm is a feasible solution to the specific problem. 1 A function is a piece of computer code that accepts
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 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 informationTentative Course Schedule, CRN INTRODUCTION TO SCIENTIFIC & ENGINEERING COMPUTING BIL 108E, CRN24023 LECTURE # 5 INLINE FUNCTIONS
Tentative Course Schedule, CRN 24023 INTRODUCTION TO SCIENTIFIC & ENGINEERING COMPUTING BIL 108E, CRN24023 Dr. S. Gökhan Technical University of Istanbul Week Date Topics 1 Feb. 08 Computing 2 Feb. 15
More informationLab of COMP 406 Introduction of Matlab (III) Programming and Scripts
Lab of COMP 406 Introduction of Matlab (III) Programming and Scripts Teaching Assistant: Pei-Yuan Zhou Contact: cspyzhou@comp.polyu.edu.hk Lab 3: 26 Sep., 2014 1 Open Matlab 2012a Find the Matlab under
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 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 informationIntroduction to MATLAB for Engineers, Third Edition
PowerPoint to accompany Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 2 Numeric, Cell, and Structure Arrays Copyright 2010. The McGraw-Hill Companies, Inc. This work is
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 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 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 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 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 informationFinding MATLAB on CAEDM Computers
Lab #1: Introduction to MATLAB Due Tuesday 5/7 at noon This guide is intended to help you start, set up and understand the formatting of MATLAB before beginning to code. For a detailed guide to programming
More informationECE Lesson Plan - Class 1 Fall, 2001
ECE 201 - Lesson Plan - Class 1 Fall, 2001 Software Development Philosophy Matrix-based numeric computation - MATrix LABoratory High-level programming language - Programming data type specification not
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 informationEng Marine Production Management. Introduction to Matlab
Eng. 4061 Marine Production Management Introduction to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment. Matlab is available
More informationVariables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:
Contents VARIABLES... 1 Storing Numerical Data... 2 Limits on Numerical Data... 6 Storing Character Strings... 8 Logical Variables... 9 MATLAB S BUILT-IN VARIABLES AND FUNCTIONS... 9 GETTING HELP IN MATLAB...
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 informationDr. Iyad Jafar. Adapted from the publisher slides
Computer Applications Lab Lab 5 Programming in Matlab Chapter 4 Sections 1,2,3,4 Dr. Iyad Jafar Adapted from the publisher slides Outline Program design and development Relational operators and logical
More informationDigital Image Analysis and Processing CPE
Digital Image Analysis and Processing CPE 0907544 Matlab Tutorial Dr. Iyad Jafar Outline Matlab Environment Matlab as Calculator Common Mathematical Functions Defining Vectors and Arrays Addressing Vectors
More informationSECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing
SECTION 5: STRUCTURED PROGRAMMING IN MATLAB ENGR 112 Introduction to Engineering Computing 2 Conditional Statements if statements if else statements Logical and relational operators switch case statements
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 informationRepetition Structures
Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements
More informationCondition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.
Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes
More informationIntroduction to MATLAB 7 for Engineers
PowerPoint to accompany Introduction to MATLAB 7 for Engineers William J. Palm III Chapter 2 Numeric, Cell, and Structure Arrays Copyright 2005. The McGraw-Hill Companies, Inc. Permission required for
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 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 information1 >> 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 informationChapter 4: Programming with MATLAB
Chapter 4: Programming with MATLAB Topics Covered: Programming Overview Relational Operators and Logical Variables Logical Operators and Functions Conditional Statements For Loops While Loops Debugging
More informationChapter 1 Introduction to MATLAB
Chapter 1 Introduction to MATLAB 1.1 What is MATLAB? MATLAB = MATrix LABoratory, the language of technical computing, modeling and simulation, data analysis and processing, visualization and graphics,
More informationExample: A Four-Node Network
Node Network Flows Flow of material, energy, money, information, etc., from one place to another arc 6 Node Node arc 6 Node Node 5 Node 6 8 Goal: Ship All of the Over the Network to Meet All of the 6 6
More informationLab 0a: Introduction to MATLAB
http://www.comm.utoronto.ca/~dkundur/course/real-time-digital-signal-processing/ Page 1 of 1 Lab 0a: Introduction to MATLAB Professor Deepa Kundur Introduction and Background Welcome to your first real-time
More informationMATLAB INTRODUCTION. Risk analysis lab Ceffer Attila. PhD student BUTE Department Of Networked Systems and Services
MATLAB INTRODUCTION Risk analysis lab 2018 2018. szeptember 10., Budapest Ceffer Attila PhD student BUTE Department Of Networked Systems and Services ceffer@hit.bme.hu Előadó képe MATLAB Introduction 2
More informationOutline. User-based knn Algorithm Basics of Matlab Control Structures Scripts and Functions Help
Outline User-based knn Algorithm Basics of Matlab Control Structures Scripts and Functions Help User-based knn Algorithm Three main steps Weight all users with respect to similarity with the active user.
More informationIntroduction to Matlab
Introduction to Matlab Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display Facilities Flow Control Using of M-File Writing User
More informationMATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab
MATH 495.3 (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab Below is a screen similar to what you should see when you open Matlab. The command window is the large box to the right containing the
More informationA = [1, 6; 78, 9] Note: everything is case-sensitive, so a and A are different. One enters the above matrix as
1 Matlab Primer The purpose of these notes is a step-by-step guide to solving simple optimization and root-finding problems in Matlab To begin, the basic object in Matlab is an array; in two dimensions,
More informationProgramming in MATLAB
trevor.spiteri@um.edu.mt http://staff.um.edu.mt/trevor.spiteri Department of Communications and Computer Engineering Faculty of Information and Communication Technology University of Malta 17 February,
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 informationProgramming 1. Script files. help cd Example:
Programming Until now we worked with Matlab interactively, executing simple statements line by line, often reentering the same sequences of commands. Alternatively, we can store the Matlab input commands
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 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 informationH.C. Chen 1/24/2019. Chapter 4. Branching Statements and Program Design. Programming 1: Logical Operators, Logical Functions, and the IF-block
Chapter 4 Branching Statements and Program Design Programming 1: Logical Operators, Logical Functions, and the IF-block Learning objectives: 1. Write simple program modules to implement single numerical
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 informationProgramming in MATLAB
Programming in MATLAB Scripts, functions, and control structures Some code examples from: Introduction to Numerical Methods and MATLAB Programming for Engineers by Young & Mohlenkamp Script Collection
More informationMATLAB: The Basics. Dmitry Adamskiy 9 November 2011
MATLAB: The Basics Dmitry Adamskiy adamskiy@cs.rhul.ac.uk 9 November 2011 1 Starting Up MATLAB Windows users: Start up MATLAB by double clicking on the MATLAB icon. Unix/Linux users: Start up by typing
More informationIntroduction to MATLAB
ELG 3125 - Lab 1 Introduction to MATLAB TA: Chao Wang (cwang103@site.uottawa.ca) 2008 Fall ELG 3125 Signal and System Analysis P. 1 Do You Speak MATLAB? MATLAB - The Language of Technical Computing ELG
More informationLaboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++
Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ 0.1 Introduction This is a session to familiarize working with the Visual Studio development environment. It
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 informationMATLAB Vocabulary. Gerald Recktenwald. Version 0.965, 25 February 2017
MATLAB Vocabulary Gerald Recktenwald Version 0.965, 25 February 2017 MATLAB is a software application for scientific computing developed by the Mathworks. MATLAB runs on Windows, Macintosh and Unix operating
More informationTeaching Manual Math 2131
Math 2131 Linear Algebra Labs with MATLAB Math 2131 Linear algebra with Matlab Teaching Manual Math 2131 Contents Week 1 3 1 MATLAB Course Introduction 5 1.1 The MATLAB user interface...........................
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 informationUnix Computer To open MATLAB on a Unix computer, click on K-Menu >> Caedm Local Apps >> MATLAB.
MATLAB Introduction This guide is intended to help you start, set up and understand the formatting of MATLAB before beginning to code. For a detailed guide to programming in MATLAB, read the MATLAB Tutorial
More informationthe Enter or Return key. To perform a simple computations type a command and next press the
Edward Neuman Department of Mathematics Southern Illinois University at Carbondale edneuman@siu.edu The purpose of this tutorial is to present basics of MATLAB. We do not assume any prior knowledge of
More informationEdward Neuman Department of Mathematics Southern Illinois University at Carbondale
Edward Neuman Department of Mathematics Southern Illinois University at Carbondale edneuman@siu.edu The purpose of this tutorial is to present basics of MATLAB. We do not assume any prior knowledge of
More informationChapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
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 informationAPPM 2460 Matlab Basics
APPM 2460 Matlab Basics 1 Introduction In this lab we ll get acquainted with the basics of Matlab. This will be review if you ve done any sort of programming before; the goal here is to get everyone on
More informationIntroduction to MATLAB
Introduction to MATLAB 1 Introduction to MATLAB A Tutorial for the Course Computational Intelligence http://www.igi.tugraz.at/lehre/ci Stefan Häusler Institute for Theoretical Computer Science Inffeldgasse
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 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 informationProgramming Exercise 1: Linear Regression
Programming Exercise 1: Linear Regression Machine Learning Introduction In this exercise, you will implement linear regression and get to see it work on data. Before starting on this programming exercise,
More informationAttia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999
Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999 1999 by CRC PRESS LLC CHAPTER THREE CONTROL STATEMENTS 3.1 FOR
More informationIntroduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003
Introduction to MATLAB Computational Probability and Statistics CIS 2033 Section 003 About MATLAB MATLAB (MATrix LABoratory) is a high level language made for: Numerical Computation (Technical computing)
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 informationDigital Image Processing
Digital Image Processing Introduction to MATLAB Hanan Hardan 1 Background on MATLAB (Definition) MATLAB is a high-performance language for technical computing. The name MATLAB is an interactive system
More informationMATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.
MATLAB Tutorial 1 1 Department of Mathematics and Statistics, The University of New Mexico, Albuquerque, NM 87131 August 28, 2016 Contents: 1. Scalars, Vectors, Matrices... 1 2. Built-in variables, functions,
More informationCS 221 Lecture. Tuesday, 13 September 2011
CS 221 Lecture Tuesday, 13 September 2011 Today s Agenda 1. Announcements 2. Boolean Expressions and logic 3. MATLAB Fundamentals 1. Announcements First in-class quiz: Tuesday 4 October Lab quiz: Thursday
More informationIntroduction to MATLAB
Outlines January 30, 2008 Outlines Part I: Part II: Writing MATLAB Functions Starting MATLAB Exiting MATLAB Getting Help Command Window Workspace Command History Current Directory Selector Real Values
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 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 informationLab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013
Lab of COMP 406 MATLAB: Quick Start Lab tutor : Gene Yu Zhao Mailbox: csyuzhao@comp.polyu.edu.hk or genexinvivian@gmail.com Lab 1: 11th Sep, 2013 1 Where is Matlab? Find the Matlab under the folder 1.
More informationMAT 343 Laboratory 2 Solving systems in MATLAB and simple programming
MAT 343 Laboratory 2 Solving systems in MATLAB and simple programming In this laboratory session we will learn how to 1. Solve linear systems with MATLAB 2. Create M-files with simple MATLAB codes Backslash
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 informationMATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano
MATLAB Lesson I Chiara Lelli Politecnico di Milano October 2, 2012 MATLAB MATLAB (MATrix LABoratory) is an interactive software system for: scientific computing statistical analysis vector and matrix computations
More informationAMS 27L LAB #1 Winter 2009
AMS 27L LAB #1 Winter 2009 Introduction to MATLAB Objectives: 1. To introduce the use of the MATLAB software package 2. To learn elementary mathematics in MATLAB Getting Started: Log onto your machine
More informationA Very Brief Introduction to Matlab
A Very Brief Introduction to Matlab by John MacLaren Walsh, Ph.D. for ECES 63 Fall 26 October 3, 26 Introduction To MATLAB You can type normal mathematical operations into MATLAB as you would in an electronic
More informationOur Strategy for Learning Fortran 90
Our Strategy for Learning Fortran 90 We want to consider some computational problems which build in complexity. evaluating an integral solving nonlinear equations vector/matrix operations fitting data
More informationAPPM 2460: Week Three For, While and If s
APPM 2460: Week Three For, While and If s 1 Introduction Today we will learn a little more about programming. This time we will learn how to use for loops, while loops and if statements. 2 The For Loop
More informationIntroduction to MATLAB
Introduction to MATLAB The Desktop When you start MATLAB, the desktop appears, containing tools (graphical user interfaces) for managing files, variables, and applications associated with MATLAB. The following
More informationEGR 111 Functions and Relational Operators
EGR 111 Functions and Relational Operators This lab is an introduction to writing your own MATLAB functions. The lab also introduces relational operators and logical operators which allows MATLAB to compare
More informationGetting To Know Matlab
Getting To Know Matlab The following worksheets will introduce Matlab to the new user. Please, be sure you really know each step of the lab you performed, even if you are asking a friend who has a better
More informationVariable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3.
MATLAB Introduction Accessing Matlab... Matlab Interface... The Basics... 2 Variable Definition and Statement Suppression... 2 Keyboard Shortcuts... More Common Functions... 4 Vectors and Matrices... 4
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 informationA Tutorial on Matlab Ch. 3 Programming in Matlab
Department of Electrical Engineering University of Arkansas A Tutorial on Matlab Ch. 3 Programming in Matlab Dr. Jingxian Wu wuj@uark.edu OUTLINE 2 Plotting M-file Scripts Functions Control Flows Exercises
More informationVARIABLES Storing numbers:
VARIABLES Storing numbers: You may create and use variables in Matlab to store data. There are a few rules on naming variables though: (1) Variables must begin with a letter and can be followed with any
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 information1 Week 1: Basics of scientific programming I
MTH739N/P/U: Topics in Scientific Computing Autumn 2016 1 Week 1: Basics of scientific programming I 1.1 Introduction The aim of this course is use computing software platforms to solve scientific and
More informationIntroduction to MATLAB LAB 1
Introduction to MATLAB LAB 1 1 Basics of MATLAB MATrix LABoratory A super-powerful graphing calculator Matrix based numeric computation Embedded Functions Also a programming language User defined functions
More informationIntroduction to Matlab
Introduction to Matlab 1 Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display Facilities Flow Control Using of M-File Writing User
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 informationIntroduction to MATLAB
Outlines September 9, 2004 Outlines Part I: Review of Previous Lecture Part II: Part III: Writing MATLAB Functions Review of Previous Lecture Outlines Part I: Review of Previous Lecture Part II: Part III:
More informationIntroduction to MATLAB
58:110 Computer-Aided Engineering Spring 2005 Introduction to MATLAB Department of Mechanical and industrial engineering January 2005 Topics Introduction Running MATLAB and MATLAB Environment Getting help
More informationBranches, Conditional Statements
Branches, Conditional Statements Branches, Conditional Statements A conditional statement lets you execute lines of code if some condition is met. There are 3 general forms in MATLAB: if if/else if/elseif/else
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 information