Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.

Slides:



Advertisements
Similar presentations
Matlab Intro Simple introduction to some basic Matlab syntax. Declaration of a variable [ ] Matrices or vectors Some special (useful) syntax. Control statements.
Advertisements

Problems and solutions Session 3. Introduction to MATLAB - Solutions 3 Problems 1. Write function Xn = mspolygon(X,x0,a) that scales the INPUT polygon.
COMP 116: Introduction to Scientific Programming Lecture 37: Final Review.
CHAPTER 5: LOOP STRUCTURES Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Programming with MATLAB
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
1 Parts of a Loop (reminder) Every loop will always contain three main elements: –Priming: initialize your variables. –Testing: test against some known.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
General Computer Science for Engineers CISC 106 Lecture 08 Dr. John Cavazos Computer and Information Sciences 2/27/2009.
CIS 101: Computer Programming and Problem Solving Lecture 5 Usman Roshan Department of Computer Science NJIT.
ENGR 111A - Spring MatLab – Palm Chapter 4, Part 4 Review and Debugging Class 12.1: Palm Chapters &
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Chapter 8 Arrays and Strings
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Fundamentals of Python: From First Programs Through Data Structures
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
Fundamentals of Python: First Programs
Matlab tutorial course Lesson 2: Arrays and data types
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
How to think through your program [ principles of good program design ] Rachel Denison MATLAB for Cognitive Neuroscience ICN, 13 December 2007.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Matlab Programming, part 1 M-files It is generally more convenient to program in Matlab using m-files, ascii text files containing a set of Matlab commands.
Matlab Programming for Engineers Dr. Nidal Farhat Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 5 – Dental Payment Application: Introducing.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
SUNY-New Paltz Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz “Lecture 6”
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Digital Image Processing Lecture10: MATLAB Example – Utility M-functions for Intensity Transformations.
Flow Control and Functions ● Script files ● If's and For's ● Basics of writing functions ● Checking input arguments ● Variable input arguments ● Output.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room , Chris Hill, Room ,
Introduction to MATLAB Session 1 Simopekka Vänskä, THL 2010.
Introduction to MATLAB Session 4 Simopekka Vänskä, THL 2010.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
Control Structures RepetitionorIterationorLooping Part I.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Introduction to Matlab Part II 1Daniel Baur / Introduction to Matlab Part II Daniel Baur / Michael Sokolov ETH Zurich, Institut für Chemie- und Bioingenieurwissenschaften.
Matlab tutorial course Lesson 4: Writing your own functions: programming constructs
Matlab Programming for Engineers
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
C++ / G4MICE Course Session 1 - Introduction Edit text files in a UNIX environment. Use the g++ compiler to compile a single C++ file. Understand the C++
Introduction to MATLAB Session 2 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2010.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Working with Loops, Conditional Statements, and Arrays.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Scripts & Functions Scripts and functions are contained in .m-files
Introduction to MATLAB
Arithmetic operations, decisions and looping
Matlab tutorial course
Presentation transcript:

Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011

Introduction to MATLAB - Session 3 Contents of this course Session 1 General Matrices M-files Session 2 Some matrix commands Logical expressions Graphics 1 Session 3 My functions + strings, cells Controlling program flow Session 4 Function functions Session 5 Graphics 2 More linear algebra Starting homework

My functions + strings and cells

Introduction to MATLAB - Session 3 Function Functions are m-files starting with command function A function creates its own variable space that includes copies of INPUT parameters  What the function does for the parameters in the function’s variable space does not effect to the calling variable space Own functions follow the same general syntax as MATLAB functions [OUTPUT parameters] = functionname(INPUT parameters); Function INPUT parameters OUTPUT parameters

Introduction to MATLAB - Session 3 Writing a function Save the function to a m-file whose name is the function name Begin with the command function, see the example. Help consisits of the first connected comment lines.  Put information! Write the command lines. Assign values for all output variables. Call the function with its name. Help by >> help ftest1 function [b,c] = ftest1(a) % function [b,c] = ftest1(a) % Function for learning functions. % INPUT: a matrix of doubles % OUTPUT: % b a short description for % c the output variables is useful. % Sp Vanska % This is not seen as help text. b = a+5; % this is a comment c = sqrt(a);

Introduction to MATLAB - Session 3 Subfunctions Some routines are practical to put to subfunctions No need for a separate m-file Start with function –command You can also write subfunctions in subfunctions.  See ”nested functions” of help for the visibility rules in this case. End with end –command (not obligatory if not nested) function Z = ftest1(X) % this is the main function % with m-file ftest1.m Y = X+2; function W = routine1(X,Y) % this is a subfunction statements end % function routine1 ends W = routine1(X,Y); Z = X+W;

Introduction to MATLAB - Session 3 Variating number of INPUT - variables Case 1: Optional variables. function z = ftest(x,p) % p optional parameter, % if p does not exist, then p = 1. if ~exist(’p’) p = 1; end Calling ftest: >> z = ftest(x,p) OR >> z = ftest(x) Case 2: Free parameter number. Use ”varargin” command: function z = ftest(x,varargin) vn = length(varargin); for j = 1:vn eval([’p’,num2str(j),’=varargin{j};’]) end To understand this, study first strings and cell arrays. In the same way: varargout

Introduction to MATLAB - Session 3 Datatype string String matrix is an array of chars. String can be created by >> s = ’abcd’; String array has to be rectangular (examples right). Related commands:  num2str, str2num: convert numbers to strings, and vice versa  eval: executes the string Try the following: >> s = [’name’;’age’] >> s = [’name’;’age1’] >> a = ’12’; >> b = 2; >> a+b >> s1 = [a,’ + ’,num2str(b)] >> s2 = str2num(a) + b >> eval(s1)

Introduction to MATLAB - Session 3 Datatype cell array Element of a cell (-array) is a matrix of any datatype  More precis, a cell element is a pointer to the matrix. Create a cell by listing the elements in curly braces, {}. Refer to the j’th element matrix: cellname{j}  Remark: cellname(j) is just the pointer to the matrix j cell(n,m) : creates (n,m) cell array of empty matrices Try the following: >> s = {’name’;’age’} >> s{1} >> s(1) >> c = {rand(3),5,’name’} >> c(1) >> c{1} >> c{1:2} >> c{1}(2,3)

Introduction to MATLAB - Session 3 …back to varargin varargin is a cell array Put varargin the last input argument Call >> z=ftest(x,q1,q2,q3); vn is the number of matrices in varargin Put the input parameters to p1, p2, … 1st round string: p1 = varargin{1}; 2nd round string: p2 = varargin{2}; etc. function z = ftest(x,varargin) vn = length(varargin); for j = 1:vn eval([’p’,num2str(j),’=varargin{j};’]) end

Controlling program flow

Introduction to MATLAB - Session 3 Program flow control Controlling what statements (commands) will be executed next Conditional control  In case A do this, but in case B do that : if, switch Loop control  Repeat the commands this many times: for  Repeat the commands until this holds: while

Introduction to MATLAB - Session 3 Conditional flow control: if – elseif – else – end General form of if statement: if logical expression 1 statements elseif logical expression 2 statements else statements end elseif is optional  There can be many elseif lines within one if-end pair else is optional  Max one else line within if- end pair Use indent when writing the if statement  Helps reading the code! TRUE FALSE TRUE FALSE

Introduction to MATLAB - Session 3 Loop flow control: for A simple form of for command: for k = 1:n statements end Repeats the statements n times  1st round, k has value 1  2nd round, k has value 2  etc. A simple generalization of for: for k = v % v vector statements end Repeats length(v) times  1st round, k has value v(1)  2nd round, k has value v(2)  etc. General form of for : for k = expression statements end Here, k runs through the columns of the expression. Try: >> for k = 1:n k end >> for k = rand(3) k end

Introduction to MATLAB - Session 3 Loop flow control: while Form of the while command: while logical expression statements end Repeats the statements until the expression is false  Avoid infinite loop! Tip: If the logical expression is complicated, or has many conditions, it is often easier to use extra logical variable: dothis = 1; loopno = 1; while dothis statements loopno = loopno+1; if (some given stop condition) dothis=0; elseif loopno>1000 dothis=0; end TRUE FALSE

Introduction to MATLAB - Session 3 Break, keyboard, return, continue BREAK terminates the loop (for or while) and program continues from end-command  In multiple loop case, only the innermost loop is terminated CONTINUE terminates this iteration of the loop and continues from the next iteration step KEYBOARD stops executing the file and gives control to user at that point.  Useful especially when debugging the code. for j=1:n … if something break end … end statement % here if break RETURN  Returns the program flow to the invoking m-file  Returns the flow to the m-file from the keyboard mode (type return + enter)

Introduction to MATLAB - Session 3 Some practical tips Long lines: [ ]; To make the code more readable  Use indents  Write comments Try to use matrices (instead of for-loops e.g.) Use profiling to speed up your programs, desktop  profiler  Some times only one routine takes most of the time  improve it!  Do not repeat the same computations  Try to minimize the arguments of the functions, e.g. only x instead of x*ones(1,1000). Keep always in your mind the memory usage.

Problems Session 3

Introduction to MATLAB - Session 3 Problems 1. Write function Xn = mspolygon(X,x0,a) that scales the INPUT polygon by a (a>0) and moves it by x0, and draws both polygons in one image.  The polygon is given by matrix X whose columns are the nodes (corner points) of the polygon. The output Xn is the nodes of new polygon.  Test your function with P of Exercise 1/Session 2.

Introduction to MATLAB - Session 3 Problems 2. Write a function Xt = roundt(X,t) that rounds real numbers to grid tZ = (…,-2t,-t,0,t,2t,…) and complex numbers to grid tC = tZ+itZ. The input X can be a matrix and t>0. Test your function (real case) with X = -5:.01:5 and t=sqrt(2)/2. Draw a picture. Test your function (complex case) with X = randn(1,5)+2*i*randn(1,5) and t=0.5. Draw a picture. Write both test cases in one m-file.

Introduction to MATLAB - Session 3 Problems 3. Continue the Triangle Exercise 7/Session 2. a) Write a function xn = Qpoints(n) where the input argument n is a vector n(j) = number of random points in [0,1]x[0,1] (e.g. n = [1,10,100,1000,10000,100000]) and xn is a cell array with xn{j} = n(j) random points in [0,1]x[0,1] i.e. matrix of size (2,n(j)). b) Call Qpoints 1000 times to find an approximative error when computing the area of T with different n’s. Represent the results graphically.

>> quit …to exit MATLAB.