Introduction. Like other programming languages, MATLAB has means for modifying the flow of a program

Size: px
Start display at page:

Download "Introduction. Like other programming languages, MATLAB has means for modifying the flow of a program"

Transcription

1 Flow control 1

2 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

3 FOR loops. If you must use a FOR loop, it is very advisable to preallocate memory for the results: for for n=1:10 x=zeros(1,10); n=1:10 x=zeros(1,10); % preallocation preallocation x(n)=sin(n*pi/10); for for n=10:-1:1 n=10:-1:1 x(n)=sin(n*pi/10); >> >> x x = Columns Columns 1 through through Columns 8 through 10 When Columns large arrays 8 through are involved, 10 preallocation saves the overhead which is incurred by allocating memory in each iteration of the loop

4 FOR loops. On the other hand, using a column vector: The loop executes only once, since the array has only one column! A FOR loop cannot be terminated by reassigning the loop variable within it An array example: i=0; i=0; for for n=(1:10) n=(1:10) i=i+1; i=i+1; End End >> >> i i = 1 i=1; i=1; for for x=rand(4,5) x=rand(4,5) y(i)=sum(x); y(i)=sum(x); i=i+1; i=i+1; >> >> y % each each element element of of y is is the the sum sum of of a column column in in x y =

5 FOR loops. FOR loops can be nested: BUT: FOR loops can often be avoided altogether by efficient programming, using vectors Vectorized code runs faster! The code below gives the same result : n=1:5; n=1:5; m=1:5; m=1:5; [nn,mm]=meshgrid(n,m); A=nn.^2+mm.^2; A=nn.^2+mm.^2; for for n=1:5 n=1:5 for for m=1:5 m=1:5 A(n,m)=n^2+m^2; A(n,m)=n^2+m^2; >> >> A A = Have a look at the meshgrid we ll discuss it later in detail 5

6 WHILE loops A group of commands is evaluated an indefinite number of times: while while expression expression (commands) (commands) The (commands) part is executed as long as ALL elements in expression are true Usually expression is a scalar, but an array is also valid e.g. computing the smallest number we can add to 1 so that the result is larger than 1: If for an array expression we wish the loop to continue when ANY element is true, use: while while any(array any(array expression) expression) (commands) (commands) num=0; num=0; EPS=1; EPS=1; while(1+eps)>1 while(1+eps)>1 EPS=EPS/2; EPS=EPS/2; num=num+1; num=num+1; EPS=EPS*2; EPS=EPS*2; >> >> num num num num = >> >> EPS EPS EPS EPS = e e-016 6

7 IF-ELSE-END constructions Conditional evaluation: The (commands) part is executed as long as ALL elements in expression are true Several more complicated constructs: expression expression (commands) (commands) expression expression (commands (commands evaluated evaluated True) True) expression1 expression1 else else (commands (commands evaluated evaluated expression1 expression1 is is True) True) (commands (commands evaluated evaluated False) False) else else expression2 expression2 (commands (commands evaluated evaluated expression2 expression2 is is True) True) else else expression3 expression3 (commands (commands evaluated evaluated expression3 expression3 is is True) True) else else (commands (commands evaluated evaluated no no expression expression is is True) True) 7

8 Example: BREAK and CONTINUE Two useful statements that can be used with conditional evaluation are break and continue break stops the FOR loop: apples=10; apples=10; cost=apples*25; cost=apples*25; apples>5 apples>5 cost=(1-20/200)*cost; continue jumps to the statement: EPS=1; EPS=1; for for num= num= 1:1000; 1:1000; EPS=EPS/2; EPS=EPS/2; (1+EPS)<=1 (1+EPS)<=1 EPS=EPS*2; EPS=EPS*2; break break EPS EPS EPS EPS = = e e-016 EPS=1; EPS=1; for for num= num= 1:1000; 1:1000; EPS=EPS/2; EPS=EPS/2; (1+EPS)>1 (1+EPS)>1 continue continue EPS=EPS*2; EPS=EPS*2; break break EPS EPS EPS EPS = = e e-016 8

9 SWITCH-CASE constructions For repeated comparison with the same variable: switch switch expression expression case case test_expression1 test_expression1 (commands1) (commands1) case case {test_expression2,test_expression3,test_expression4} (commands2) (commands2) otherwise otherwise (commands3) (commands3) expression must be a scalar or a string Scalar: it is compared to each test_expression String: compared with strcmp to each test_expression In the case of a cell array as above comparison is carried out to each of the elements When the comparison is True, the appropriate (commands) are executed 9

10 SWITCH-CASE constructions At most only one command group will be executed! x=2.7; x=2.7; units= units= 'm' 'm' ; ; switch switch units units case case {'inch','in'} {'inch','in'} y=x*2.54; y=x*2.54; case case {'feet','ft'} {'feet','ft'} y=x*2.54*12; y=x*2.54*12; case case {'meter','m'} {'meter','m'} y=x*100; y=x*100; case case {'millimeter','mm'} {'millimeter','mm'} y=x/10; y=x/10; otherwise otherwise disp(['unknown disp(['unknown Units: Units: ',units]) ',units]) y=nan; y=nan; Result: y=270 10

11 TRY-CATCH constructions For error trapping : try try (commands1) (commands1) catch catch (commands2) (commands2) All expressions in (commands1) are executed If no errors are generated control passes to If an error appears then (commands2) are executed Variable lasterr in the catch block contains the string generated by the error 11

12 TRY-CATCH constructions Example: >> >> x=ones(1,3); x=ones(1,3); >> >> y=zeros(1,4); y=zeros(1,4); try try z=x*y; z=x*y; catch catch z=nan; z=nan; disp('nooo! disp('nooo! ') ') nooo! nooo! >> >> z z = NaN NaN Last error: >> >> lasterr lasterr ans ans = Error Error using using ==> ==> * Inner Inner matrix matrix dimensions dimensions must must agree. agree. 12

13 Function M-files 13

14 Introduction: Template of calling syntax code Script M-files enable us to run a set of MATLAB commands without the need to type them all every time They interact with all the variables in the workspace Function M-files are like Matlab s: they receive arguments and return results Intermediate variables created in a are erased when the terminates Example: Usage info for help command res=dosomework(a,b) %DOSOMEWORK %DOSOMEWORK An An example example of of a that that does does something something % dosomework(a,b) dosomework(a,b) takes takes a or or b randomly randomly % % Example: Example: who who needs needs examples? examples? % See See also also DONOWORK, DONOWORK, WORKALITTLE WORKALITTLE ind=round(rand(1,1)); res=[a,b]; res=[a,b]; res=res(ind+1); res=res(ind+1); 14

15 Some notes: The first line starts with the word The rest of the line defines the input and output variables Function files have the same extension as a script file:.m There is no return statement at the of a The continuous sequence of comment lines are the text displayed in response to help dosomework or helpwin dosomework The first help line, called the H1 line is the line search by the lookfor command 15

16 Running the example : We call the dosomework like it was any Matlab Internal Variables ind and res are not recognized after the has terminated res=dosomework(a,b) res=dosomework(a,b) %DOSOMEWORK %DOSOMEWORK An An example example of of a a % dosomework(a,b) takes a or b randomly % dosomework(a,b) takes a or b randomly % % % % Example: Example: who who needs needs examples? examples? % See also DONOWORK, WORKALITTLE % See also DONOWORK, WORKALITTLE ind=round(rand(1,1)); ind=round(rand(1,1)); res=[a,b]; res=[a,b]; res=res(ind+1); res=res(ind+1); The result of the can be assigned to a variable: The variable a in the main workspace has no connection to the variable a in the 16

17 Input and output arguments: Function M-files can have zero input and zero output arguments Functions can be called with fewer input and output arguments then those that appear in the definition line but NOT more The number of input and output arguments used in a call can be determined by calling nargin and nargout: y=mmdigit(x,n,b,t) y=mmdigit(x,n,b,t) %MMDIGIT Round Values to Given Signicant Digits. (MM) %MMDIGIT Round Values to Given Signicant Digits. (MM) % MMDIGIT(X,N,B) rounds array X to N signicant places in base B. % MMDIGIT(X,N,B) rounds array X to N signicant places in base B. % If B is not given, B=10 is assumed. % If B is not given, B=10 is assumed. % If X is complex the real and imaginary parts are rounded separately. % If X is complex the real and imaginary parts are rounded separately. % MMDIGIT(X,N,B,'fix') uses FIX instead of ROUND. % MMDIGIT(X,N,B,'fix') uses FIX instead of ROUND. % MMDIGIT(X,N,B,'ceil') uses CEIL instead of ROUND. % MMDIGIT(X,N,B,'ceil') uses CEIL instead of ROUND. % MMDIGIT(X,N,B,'floor') uses FLOOR instead of ROUND. % MMDIGIT(X,N,B,'floor') uses FLOOR instead of ROUND. nargin<2 nargin<2 error('not enough input arguments.') error('not enough input arguments.') else nargin==2 else nargin==2 b=10; b=10; t='round'; t='round'; else nargin==3 else nargin==3 t='round'; t='round'; 17

18 Input and output arguments- cont. Input variables are not copied into the workspace, except they are modied If nothing is assigned to output variables no output occurs. Trying to assign the result to a variable will give an error. For advanced programmers: A variable, unlimited number of input arguments can be passed using varargin, which becomes a cell array. It can be mixed with other inputs, but must be the last: y=myfunc(x,n,b,t,varargin) y=myfunc(x,n,b,t,varargin) nargin counts each cell as a dferent input variable. A variable, unlimited number of output arguments can be passed using varargout, which must be a cell array [a,b,varagout]y=myfunc(x) [a,b,varagout]y=myfunc(x) 18

19 Function workspaces All variables created in a are hidden from the MATLAB base workspace These variables reside in a temporary workspace (the workspace) created with each call and deleted when the terminates If a is stopped temporarily, e.g. by the keyboard command the workspace is active, not the base workspace Certain techniques are available for communication among the workspaces and the base workspace 19

20 Linking the and base workspaces basic method 1: 1) GLOBAL variables Functions can share global variables with other s and the MATLAB base workspace These are declared by: global varname. In order to be recognized in the base workspace, they must be declared global there also. Example: timing a set of commands with tic and toc tic tic Global Global TICTOC TICTOC TICTOC=clock; TICTOC=clock; y=toc y=toc Global Global TICTOC TICTOC y=etime(clock,tictoc); y=etime(clock,tictoc); Calling syntax: >> >> tic,(command),toc tic,(command),toc Usage: 20

21 Linking the and base workspaces basic method 2: 2) Persistent variables Functions can share variables with repeated or recursive calls to themselves These are declared by: persistent varname Example: persisty persisty persistent persistent threshold threshold isempty(threshold) isempty(threshold) threshold=1 threshold=1 else else threshold=threshold*.5 threshold=threshold*.5 Note: persisent variables are initially empty 21

22 Linking the and base workspaces advanced methods 1) Evalin An expression can be evaluated in another workspace: either in the calling workspace or the base workspace, using: a=evalin( caller, expression ) a=evalin( base, expression ) a=evalin( caller, try, catch ) a=evalin( base, try, catch ) Note: catch is evaluated in the current workspace try creates an error in the base or caller workspace 22

23 Linking the and base workspaces advanced methods 2) assignin Assigning can also be performed in another workspace using: assignin( workspace, vname,x) where workspace is either caller or base. This assigns the content of variable X to a variable named vname in the base or caller workspace. 3) inputname With this you can determine the variable names that were used when the was called. After a call: >> y=my(xdot,time,sqrt(2)) >> y=my(xdot,time,sqrt(2)) inputname (1) inside the gives xdot as a character string, but inputname(3) gives an empty array because the third argument is an expression, not a name. 23

24 M-file construction rules: The name of the M-file should be identical to the name in the first line of the Function M-file names can have up to 31 characters Case sensitivity deps on platform it is recommed to use only lowercase letters. Function names must begin with a letter. Any combination of letters, numbers and underscores can appear afterwards. The first line of a is called the -declaration line and must contain the word followed by the calling syntax. The input and output variables are local to the A terminates after the last line OR whenever a return statement is encountered Function M-files can contain calls to script files. Scripts are evaluated in the s workspace, not the base workspace 24

25 M-file construction rules cont.: A can abort execution by calling the error. This can be used for flagging improper usage as in: length(val)>1 length(val)>1 error( VAL error( VAL must must be be a scalar. ) scalar. ) A can report a warning and continue by calling the warning( a message ). Note: Warnings can be turned on or off globally with warning on or warning off 25

26 Subs and private s Multiple s can appear in a single M-file. Additional subs or local s are apped to the primary and follow construction rules. Subs can be called by the primary in the M-file as well as other subs in the M-file. Help is obtained for subs by typing >> help func>subfunc M-files can also call private M-files which are standard M-files that reside in a subdirectory of the calling titled private. 26

27 Command- duality In addition to M-files, it is possible to create MATLAB commands such as clear, dir, ver, etc. Commands are similar to s, except: Commands do not have output arguments Input arguments are not enclosed in parentheses In fact any can be called as a command and any command can be called as a! Calling a MATLAB command as a : >> >> dir dir *.mat *.mat noamdata.mat noamdata.mat test.mat test.mat >> >> a=dir('*.mat') a=dir('*.mat') a a = = 2x1 2x1 struct struct array array with with fields: fields: name name date date bytes bytes isdir isdir 27

28 Command- duality cont. Rules for calling a MATLAB command as a : A MATLAB command with any number of arguments can be called as a with each argument in quotes The result, it exists can be assigned to a variable Assigning can be performed ONLY in the call form Calling a user defined as a command: Any user defined can be called as a command All arguments are passed to the as strings This can be misleading! y=test(a,b) y=test(a,b) y=a+b; y=a+b; >> >> test(21,22) test(21,22) ans ans = = >> >> test test ans ans = = In the example on the right: The numbers were interpreted as strings, and their ASCII values were summed! 28

29 Function evaluation with feval Sometimes a character string of a is passed to a for evaluation (e.g. in solving dferential equations) The can then be evaluated in a number of ways: >> >> [a,b]=feval( my,x,y,z,t) >> >> [a,b]=eval( my(x,y,z,y) ) eval calls the entire MATLAB interpreter, thus it is much less efficient than feval feval can be further speed up by passing it a handle instead of a string: >> fhan=@humps >> fhan=@humps >> >> [a,b]=feval(fhan,x,y,z,t) Function handles can also be arrays: >> >> fhan(1)=@humps fhan(1)=@humps >> >> fhan(2)=@cos fhan(2)=@cos 29

30 feval The content of a file handle can be examined in detail with the s command: >> >> fhan=@humps fhan=@humps >> >> s(fhan) s(fhan) ans ans = : : 'humps' 'humps' type: type: 'simple' 'simple' file: file: 'c:\matlab6p5\toolbox\matlab\demos\humps.m' A string to be evaluated can also be converted into an inline and assigned a handle: The old way: and >> >> myfun='x^2+y^2'; myfun='x^2+y^2'; >> >> x=2;y=3;eval(myfun) ans ans =

31 feval The new way: >> >> myfuni=inline(myfun,'x','y') myfuni myfuni = Inline Inline : : myfuni(x,y) myfuni(x,y) = x^2+y^2 x^2+y^2 >> >> a=feval(myfuni,2,3) a = Queries into the inline : For more info on how to deal with all these look also into fcnchk >> >> argnames(myfuni) argnames(myfuni) ans ans = 'x' 'x' 'y' 'y' >> >> formula(myfuni) formula(myfuni) ans ans = x^2+y^2 x^2+y^2 31

Introduction. Like other programming languages, MATLAB has means for modifying the flow of a program

Introduction. 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 modifying the flow of a program All common constructs are implemented in MATLAB: for while if then else switch try 2 FOR

More information

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

INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD. July 2018

INTRODUCTION 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 information

Computational Methods of Scientific Programming

Computational Methods of Scientific Programming 12.010 Computational Methods of Scientific Programming Lecturers Thomas A Herring, Jim Elliot, Chris Hill, Summary of Today s class We will look at Matlab: History Getting help Variable definitions and

More information

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

Variables 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 information

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

Introduction 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 information

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB

SECTION 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 information

Chapters 6-7. User-Defined Functions

Chapters 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 information

Introduction to MATLAB

Introduction 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 information

EL2310 Scientific Programming

EL2310 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 information

MAT 343 Laboratory 2 Solving systems in MATLAB and simple programming

MAT 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 information

ECE Lesson Plan - Class 1 Fall, 2001

ECE 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 information

User Defined Functions

User 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 information

LECTURE 1. What Is Matlab? Matlab Windows. Help

LECTURE 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 information

EL2310 Scientific Programming

EL2310 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 information

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Constraint-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 information

Question Points Score Total 100

Question 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 information

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221

1 >> 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 information

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

SECTION 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 information

Chapter 3: Programming with MATLAB

Chapter 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 information

A control expression must evaluate to a value that can be interpreted as true or false.

A control expression must evaluate to a value that can be interpreted as true or false. Control Statements Control Expressions A control expression must evaluate to a value that can be interpreted as true or false. How a control statement behaves depends on the value of its control expression.

More information

10 M-File Programming

10 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 information

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225

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 information

Introduction to MATLAB

Introduction 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 information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY What is MATLAB? MATLAB (MATrix LABoratory) developed by The Mathworks, Inc. (http://www.mathworks.com) Key Features: High-level language for numerical

More information

9/4/2018. Chapter 2 (Part 1) MATLAB Basics. Arrays. Arrays 2. Arrays 3. Variables 2. Variables

9/4/2018. Chapter 2 (Part 1) MATLAB Basics. Arrays. Arrays 2. Arrays 3. Variables 2. Variables Chapter 2 (Part 1) MATLAB Basics Arrays The fundamental unit of data in MATLAB is the array. An array is a collection of data values organized into rows and columns and is known by a specified name. Individual

More information

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

SECTION 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 information

Shell CSCE 314 TAMU. Haskell Functions

Shell CSCE 314 TAMU. Haskell Functions 1 CSCE 314: Programming Languages Dr. Dylan Shell Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions can

More information

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP) Digital Signal Processing Prof. Nizamettin AYDIN naydin@yildiz.edu.tr naydin@ieee.org http://www.yildiz.edu.tr/~naydin Course Details Course Code : 0113620 Course Name: Digital Signal Processing (Sayısal

More information

Lecturer: Keyvan Dehmamy

Lecturer: Keyvan Dehmamy MATLAB Tutorial Lecturer: Keyvan Dehmamy 1 Topics Introduction Running MATLAB and MATLAB Environment Getting help Variables Vectors, Matrices, and linear Algebra Mathematical Functions and Applications

More information

MATLAB Introductory Course Computer Exercise Session

MATLAB Introductory Course Computer Exercise Session MATLAB Introductory Course Computer Exercise Session This course is a basic introduction for students that did not use MATLAB before. The solutions will not be collected. Work through the course within

More information

Title. Syntax. stata.com. function. void [ function ] declarations Declarations and types. declaration 1 fcnname(declaration 2 ) { declaration 3

Title. Syntax. stata.com. function. void [ function ] declarations Declarations and types. declaration 1 fcnname(declaration 2 ) { declaration 3 Title stata.com declarations Declarations and types Syntax Description Remarks and examples Also see Syntax such as declaration 1 fcnname(declaration 2 ) declaration 3 real matrix myfunction(real matrix

More information

MATLAB Second Seminar

MATLAB 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 information

function [s p] = sumprod (f, g)

function [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 information

Programming in MATLAB

Programming 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 information

Introduction to Matlab. By: Hossein Hamooni Fall 2014

Introduction to Matlab. By: Hossein Hamooni Fall 2014 Introduction to Matlab By: Hossein Hamooni Fall 2014 Why Matlab? Data analytics task Large data processing Multi-platform, Multi Format data importing Graphing Modeling Lots of built-in functions for rapid

More information

Chemical Engineering 541

Chemical Engineering 541 Chemical Engineering 541 Computer Aided Design Methods Matlab Tutorial 1 Overview 2 Matlab is a programming language suited to numerical analysis and problems involving vectors and matricies. Matlab =

More information

This is the basis for the programming concept called a loop statement

This is the basis for the programming concept called a loop statement Chapter 4 Think back to any very difficult quantitative problem that you had to solve in some science class How long did it take? How many times did you solve it? What if you had millions of data points

More information

An Introduction to Matlab5

An Introduction to Matlab5 An Introduction to Matlab5 Phil Spector Statistical Computing Facility University of California, Berkeley August 21, 2006 1 Background Matlab was originally developed as a simple interface to the LINPACK

More information

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

ELEC4042 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 information

Structure Array 1 / 50

Structure 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 information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

Introduction 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 information

Selection Statements. Chapter 4. Copyright 2013 Elsevier Inc. All rights reserved 1

Selection Statements. Chapter 4. Copyright 2013 Elsevier Inc. All rights reserved 1 Selection Statements Chapter 4 Copyright 2013 Elsevier Inc. All rights reserved 1 Recall Relational Expressions The relational operators in MATLAB are: > greater than < less than >= greater than or equals

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

MATLAB The first steps. Edited by Péter Vass

MATLAB The first steps. Edited by Péter Vass MATLAB The first steps Edited by Péter Vass MATLAB The name MATLAB is derived from the expression MATrix LABoratory. It is used for the identification of a software and a programming language. As a software,

More information

Flow Control and Functions

Flow 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 information

Introduction to MATLAB

Introduction to MATLAB Computational Photonics, Seminar 0 on Introduction into MATLAB, 3.04.08 Page Introduction to MATLAB Operations on scalar variables >> 6 6 Pay attention to the output in the command window >> b = b = >>

More information

Hava Language Technical Reference

Hava Language Technical Reference Hava Language Technical Reference April 25, 2009 (draft) Steven T. Hackman, Loren K. Platzman H. Milton Stewart School of Industrial and Systems Engineering Georgia Institute of Technology Hava is a numerical

More information

Interactive MATLAB use. Often, many steps are needed. Automated data processing is common in Earth science! only good if problem is simple

Interactive MATLAB use. Often, many steps are needed. Automated data processing is common in Earth science! only good if problem is simple Chapter 2 Interactive MATLAB use only good if problem is simple Often, many steps are needed We also want to be able to automate repeated tasks Automated data processing is common in Earth science! Automated

More information

Chapter 7: Programming in MATLAB

Chapter 7: Programming in MATLAB The Islamic University of Gaza Faculty of Engineering Civil Engineering Department Computer Programming (ECIV 2302) Chapter 7: Programming in MATLAB 1 7.1 Relational and Logical Operators == Equal to ~=

More information

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements Programming Languages Third Edition Chapter 9 Control I Expressions and Statements Objectives Understand expressions Understand conditional statements and guards Understand loops and variation on WHILE

More information

H.C. Chen 1/24/2019. Chapter 4. Branching Statements and Program Design. Programming 1: Logical Operators, Logical Functions, and the IF-block

H.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 information

VARIABLES Storing numbers:

VARIABLES 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 information

MATLAB Operators, control flow and scripting. Edited by Péter Vass

MATLAB Operators, control flow and scripting. Edited by Péter Vass MATLAB Operators, control flow and scripting Edited by Péter Vass Operators An operator is a symbol which is used for specifying some kind of operation to be executed. An operator is always the member

More information

Machine Learning Exercise 0

Machine Learning Exercise 0 Machine Learning Exercise 0 Introduction to MATLAB 19-04-2016 Aljosa Osep RWTH Aachen http://www.vision.rwth-aachen.de osep@vision.rwth-aachen.de 1 Experiences with Matlab? Who has worked with Matlab before?

More information

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

MATLAB 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 information

Part #1. A0B17MTB Matlab. Miloslav Čapek Filip Kozák, Viktor Adler, Pavel Valtr

Part #1. A0B17MTB Matlab. Miloslav Čapek Filip Kozák, Viktor Adler, Pavel Valtr A0B17MTB Matlab Part #1 Miloslav Čapek miloslav.capek@fel.cvut.cz Filip Kozák, Viktor Adler, Pavel Valtr Department of Electromagnetic Field B2-626, Prague You will learn Scalars, vectors, matrices (class

More information

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words. , ean, arithmetic s s on acters Comp Sci 1570 Introduction to C++ Outline s s on acters 1 2 3 4 s s on acters Outline s s on acters 1 2 3 4 s s on acters ASCII s s on acters ASCII s s on acters Type: acter

More information

8. Control statements

8. Control statements 8. Control statements A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon

More information

General Information. There are certain MATLAB features you should be aware of before you begin working with MATLAB.

General Information. There are certain MATLAB features you should be aware of before you begin working with MATLAB. Introduction to MATLAB 1 General Information Once you initiate the MATLAB software, you will see the MATLAB logo appear and then the MATLAB prompt >>. The prompt >> indicates that MATLAB is awaiting a

More information

Computer Vision 2 Exercise 0. Introduction to MATLAB ( )

Computer Vision 2 Exercise 0. Introduction to MATLAB ( ) Computer Vision 2 Exercise 0 Introduction to MATLAB (21.04.2016) engelmann@vision.rwth-aachen.de, stueckler@vision.rwth-aachen.de RWTH Aachen University, Computer Vision Group http://www.vision.rwth-aachen.de

More information

Desktop Command window

Desktop 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 information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

MATLAB 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 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 information

Programming for Experimental Research. Flow Control

Programming for Experimental Research. Flow Control Programming for Experimental Research Flow Control FLOW CONTROL In a simple program, the commands are executed one after the other in the order they are typed. Many situations require more sophisticated

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Modeling and Simulating Social Systems with MATLAB

Modeling and Simulating Social Systems with MATLAB Modeling and Simulating Social Systems with MATLAB Lecture 6 Optimization and Parallelization Olivia Woolley, Tobias Kuhn, Dario Biasini, Dirk Helbing Chair of Sociology, in particular of Modeling and

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

Chapter 9: Dealing with Errors

Chapter 9: Dealing with Errors Chapter 9: Dealing with Errors What we will learn: How to identify errors Categorising different types of error How to fix different errors Example of errors What you need to know before: Writing simple

More information

MATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs

MATLAB Laboratory 10/07/10 Lecture. Chapter 7: Flow Control in Programs MATLAB Laboratory 10/07/10 Lecture Chapter 7: Flow Control in Programs Lisa A. Oberbroeckling Loyola University Maryland loberbroeckling@loyola.edu L. Oberbroeckling (Loyola University) MATLAB 10/07/10

More information

22-Functions Part 1 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

22-Functions Part 1 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie 22-Functions Part 1 text: Chapter 7.1-7.5 ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie Overview Function Syntax Help Line Saving Functions Using Functions Dr. Henry Louie 2 Function

More information

COMP MATLAB.

COMP MATLAB. COMP110031 MATLAB chenyang@fudan.edu.cn M 2 M 3 M 4 M 5 M 6 M script MATLAB MATLAB 7 M function M function [y1,...,yn] = myfunc(x1,...,xm) myfunc x1,...,xm y1,...,yn eters 8 function y=myfunc(x) y=x+1;

More information

Introduction to MATLAB

Introduction 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 information

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis Introduction to Matlab 1 Outline What is Matlab? Matlab desktop & interface Scalar variables Vectors and matrices Exercise 1 Booleans Control structures File organization User defined functions Exercise

More information

University of Alberta

University of Alberta A Brief Introduction to MATLAB University of Alberta M.G. Lipsett 2008 MATLAB is an interactive program for numerical computation and data visualization, used extensively by engineers for analysis of systems.

More information

XQ: An XML Query Language Language Reference Manual

XQ: An XML Query Language Language Reference Manual XQ: An XML Query Language Language Reference Manual Kin Ng kn2006@columbia.edu 1. Introduction XQ is a query language for XML documents. This language enables programmers to express queries in a few simple

More information

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors. 1 LECTURE 3 OUTLINES Variable names in MATLAB Examples Matrices, Vectors and Scalar Scalar Vectors Entering a vector Colon operator ( : ) Mathematical operations on vectors examples 2 VARIABLE NAMES IN

More information

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations MATLAB Tutorial The following tutorial has been compiled from several resources including the online Help menu of MATLAB. It contains a list of commands that will be directly helpful for understanding

More information

Introduction to Matlab

Introduction to Matlab Introduction to Matlab This tour introduces the basic notions of programming with Matlab. Contents M-file scripts M-file functions Inline functions Loops Conditionals References M-file scripts A script

More information

Step by step set of instructions to accomplish a task or solve a problem

Step by step set of instructions to accomplish a task or solve a problem Step by step set of instructions to accomplish a task or solve a problem Algorithm to sum a list of numbers: Start a Sum at 0 For each number in the list: Add the current sum to the next number Make the

More information

MATLAB BASICS. M Files. Objectives

MATLAB BASICS. M Files. Objectives Objectives MATLAB BASICS 1. What is MATLAB and why has it been selected to be the tool of choice for DIP? 2. What programming environment does MATLAB offer? 3. What are M-files? 4. What is the difference

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,

More information

YOLOP Language Reference Manual

YOLOP Language Reference Manual YOLOP Language Reference Manual Sasha McIntosh, Jonathan Liu & Lisa Li sam2270, jl3516 and ll2768 1. Introduction YOLOP (Your Octothorpean Language for Optical Processing) is an image manipulation language

More information

CSE P 501 Exam 12/1/11

CSE P 501 Exam 12/1/11 Name There are 7 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. You may refer to the following references:

More information

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk

Control Statements. Objectives. ELEC 206 Prof. Siripong Potisuk Control Statements ELEC 206 Prof. Siripong Potisuk 1 Objectives Learn how to change the flow of execution of a MATLAB program through some kind of a decision-making process within that program The program

More information

An Introduction to MATLAB

An Introduction to MATLAB An Introduction to MATLAB Day 1 Simon Mitchell Simon.Mitchell@ucla.edu High level language Programing language and development environment Built-in development tools Numerical manipulation Plotting of

More information

EVAL FUNCTION. eval Execute a string containing a MATLAB expression

EVAL FUNCTION. eval Execute a string containing a MATLAB expression EVAL FUNCTION eval Execute a string containing a MATLAB expression Syntax The eval command is one of the most powerful and flexible commands in MATLAB. eval is short for evaluate, which is exactly what

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Matlab Programming MET 164 1/24

Matlab Programming MET 164 1/24 Matlab Programming 1/24 2/24 What does MATLAB mean? Contraction of Matrix Laboratory Matrices are rectangular arrays of numerical values 7 3 6 2 1 9 4 4 8 4 1 5 7 2 1 3 What are the fundamental components

More information

INTRODUCTION TO MATLAB. Padmanabhan Seshaiyer

INTRODUCTION TO MATLAB. Padmanabhan Seshaiyer INTRODUCTION TO MATLAB First Steps You should start MATLAB by simply typing matlab if you are working on a Unix system or just by double clicking the MATLAB icon if you are using a Windows based system.

More information

Matlab- Command Window Operations, Scalars and Arrays

Matlab- Command Window Operations, Scalars and Arrays 1 ME313 Homework #1 Matlab- Command Window Operations, Scalars and Arrays Last Updated August 17 2012. Assignment: Read and complete the suggested commands. After completing the exercise, copy the contents

More information

A BRIEF INTRODUCTION TO MATLAB Fotios Kasolis Introduction

A BRIEF INTRODUCTION TO MATLAB Fotios Kasolis Introduction A BRIEF INTRODUCTION TO MATLAB Fotios Kasolis 2008-2009 Contents 1. Introduction...................................... 1 2. Asking for help...................................... 2 3. Variables and assignments......................................

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) Introduction This semester, through a project split into 3 phases, we are going

More information

Dr. Khaled Al-Qawasmi

Dr. Khaled Al-Qawasmi Al-Isra University Faculty of Information Technology Department of CS Programming Mathematics using MATLAB 605351 Dr. Khaled Al-Qawasmi ١ Dr. Kahled Al-Qawasmi 2010-2011 Chapter 3 Selection Statements

More information

19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd

19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd 19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd Will you walk a little faster? said a whiting to a snail, There s a porpoise close behind us, and he s treading

More information