Matlab Training Session 4: Control, Flow and Functions

Slides:



Advertisements
Similar presentations
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Advertisements

Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
ITEC113 Algorithms and Programming Techniques
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Scripts and Flow Control. Scripts So far we have been entering commands directly into the command line But there is a better way Script files (and functions)
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Lecture 12 Another loop for repetition The while loop construct © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Programming in MATLAB Week 14 – 4/28/09 Kate Musgrave
Extending MATLAB Write your own scripts and/or functions Scripts and functions are plain text files with extension.m (m-files) To execute commands contained.
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
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.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Objectives Understand what MATLAB is and why it is widely used in engineering and science Start the MATLAB program and solve simple problems in the command.
How to think through your program [ principles of good program design ] Rachel Denison MATLAB for Cognitive Neuroscience ICN, 13 December 2007.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (1): Introduction.
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
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.
MATLAB Harri Saarnisaari, Part of Simulations and Tools for Telecommunication Course.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
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.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
Matlab Beginner Training Session Review: Introduction to Matlab for Graduate Research.
Extending MATLAB Write your own scripts and/or functions Scripts and functions are plain text files with extension.m (m-files) To execute commands contained.
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
Introduction to Programming on MATLAB Ecological Modeling Course Sep 11th, 2006.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
EEE 161 Applied Electromagnetics
REPETITION CONTROL STRUCTURE
Computer Application in Engineering Design
Topics Introduction to Repetition Structures
L – Modeling and Simulating Social Systems with MATLAB
CS1371 Introduction to Computing for Engineers
Chapter 4 Select…Case Multiple-Selection Statement & Logical Operators
Scripts & Functions Scripts and functions are contained in .m-files
Programming Fundamentals
MATLAB DENC 2533 ECADD LAB 9.
User Defined Functions
Chapter 4 Select…Case Multiple-Selection Statement & Logical Operators
Week 8 - Programming II Today – more features: Loop control
Lecture 1: Introduction
Conditions and Ifs BIS1523 – Lecture 8.
MATH 493 Introduction to MATLAB
CS100J 26 April. Matlab Use help button!!! Variables, values, types
Use of Mathematics using Technology (Maltlab)
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Structured Program
T. Jumana Abu Shmais – AOU - Riyadh
Loops CIS 40 – Introduction to Programming in Python
Introduction to TouchDevelop
Matlab Training Session 5: Importing Data
Chapter 4 Select…Case Multiple-Selection Statement & Logical Operators
CSCI N317 Computation for Scientific Applications Unit 1 – 1 MATLAB
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.
Matlab Training Session 2: Matrix Operations and Relational Operators
Selection Statements Chapter 3.
Matlab Basics Tutorial
Week 7: Computer Tools for Problem Solving and Critical Thinking
Presentation transcript:

Matlab Training Session 4: Control, Flow and Functions

Course Outline Weeks: Introduction to Matlab and its Interface (Jan 13 2009) Fundamentals (Operators) Fundamentals (Flow) Importing Data Functions and M-Files Plotting (2D and 3D) Statistical Tools in Matlab Analysis and Data Structures Course Website: http://www.queensu.ca/neurosci/matlab.php

Fundamentals of Matlab 4 Week 4 Lecture Outline Fundamentals of Matlab 4 A. Week 3 Review B. Functions in Matlab C. Mini Project

Matlab Scripts Entering Multiple Lines Without Running Them Matlab can execute sequences of commands stored in files Files that contain matlab commands have the extension ‘*.m’ *.m files are written and saved in the built in matlab m-file editor M-files are executed from the M-file editor or the command prompt M-files can call other M-files **The location path of the M-file must be set in matlab

Matlab Scripts Advantages of M-files Easy editing and saving of work Undo changes Readability/Portability - non executable comments can be added using the ‘%’ symbol to make make commands easier to understand Saving M-files is far more memory efficient than saving a workspace

Week 2 Review Relational Operators < less than Relational operators are used to compare two scaler values or matrices of equal dimensions < less than <= less than or equal to > Greater than >= Greater than or equal to == equal ~= not equal

Condition Statements It is often necessary to only perform matlab operations when certain conditions are met Relational and Logical operators are used to define specific conditions Simple flow control in matlab is performed with the ‘If’, ‘Else’, ‘Elseif’ and ‘Switch’ statements

Condition Statements If, Else, and Elseif if logical_expression An if statement evaluates a logical expression and evaluates a group of commands when the logical expression is true The list of conditional commands are terminated by the end statement If the logical expression is false, all the conditional commands are skipped Execution of the script resumes after the end statement Basic form: if logical_expression commands end

Condition Statements If, Else, and Elseif The elseif statement forces execution of the commands below the else statement if the original logical expression evaluates to false Only one list of commands can be executed Basic form: if logical_expression commands 1 elseif logical_expression_2 commands 2 elseif logical_expression_3 commands 3 end

Loops Loops are an important component of flow control that enables matlab to repeat multiple statements in specific and controllable ways Simple repetition in matlab is controlled by two types of loops: For loops While loops

Loops For Loops The for loop executes a statement or group of statements a predetermined number of times Basic Form: for index = start:increment:end statements end ** If ‘increment’ is not specified, an increment of 1 is assumed by matlab

Loops While Loops The while loop executes a statement or group of statements repeatedly as long as the controlling expression is true Basic Form: while expression statements end

Functions Building blocks of programming Allow code to be generic and reusable Design from top down but build from bottom up Take a set of inputs, perform a series of manipulations and return an output

Functions in Matlab In Matlab, each function is a .m file It is good protocol to name your .m file the same as your function name, i.e. funcname.m function outargs=funcname(inargs); Function input output

Simple Example Find the cube of a number -> (x3) Type the code below into an .m file and save it as cube.m Set the Matlab directory appropriately In Matlab window, type cube(3), is the result correct? Now you have a reusable function that can calculate the cube of any number >> cube(3) Ans = 125 >> cube 1.75 Ans = 5.3594 function [y] = cube(x) y = x*x*x;

Add Some Help Find the cube of a number -> (x3) Add commented text between the funciton declaration and the first line of code Now type help cube in Matlab window function [y] = cube(x) % Put some text here y = x*x*x; >> help cube Put some text here

Find the cube of two numbers Any numbers of inputs and outputs can be handled in a function For a simple example, extend the cube function to accept two inputs and find the cube of each function [y1, y2] = cube(x1, x2) % Put some text here y1 = x1*x1*x1; y2 = x2*x2*x2; >> cube(2,3) Ans = 8 ??? >> [a b] = cube(2,3) a = 8 b = 27

nargin Matlab will accept a function call with any number of inputs and outputs nargin can be used to find out how many inputs the user has provided It is automatically passed with the function function [y1, y2] = cube(x1, x2) if nargin == 1 y1 = x1*x1*x1; y2 = nan; elseif nargin == 2 y2 = x2*x2*x2; end >> cube(2,3) Ans = 8 >> [a b] = cube(2,3) a = 8 b = 27

return return terminates computation of the function and returns whatever is calculated thus far function [y1, y2] = cube(x1, x2) if nargin == 1 y1 = x1*x1*x1; y2 = nan; return end y2 = x2*x2*x2; >> cube(2,3) Ans = 8 >> [a b] = cube(2,3) a = 8 b = 27

Find the Cube of Any Number of Numbers Any ideas on how to accomplish this? Lets further extend the function to cube a vector of numbers Before we thought of the variables as scalars, now rethink the power of vectors >> cube(2) Ans = 8 >> cube([2 3]) Ans = [8 27] function [y] = cube(x) % Put some text here y = x.^3;

Mini-Project Lets combine what we have learned thus far in the course Loops, If Statements, Functions Basic Matlab Operators Should finish this in class today If you get through this then you are doing well

Mini-Project Raising any number of numbers to the nth power Inputs: A vector of numbers to be raised (N1…Nm) A vector of powers (P1…Pm) Outputs: A vector of raised values (N1P1 … NmPm) An error flag: 1 if error in calculation, 0 if successful Caveats: If only one input is provided, the function should square each entry, so output = (N12…Nm2) and error flag is 0 If the length of N and P are not the same, this is an error, return anything in the output vector and a 1 in the error flag Make sure to comment and document the function

Mini-Project Plan before you code Remember that xn=x*x*x*x … *x (n times) Hint: remember the built in functions ‘length’ and ‘size’ will return the dimensions of any given variable Ask questions and take your time

Solution 1 (simple) function [y, e] = raise(x,n) if nargin == 1 y = x.^2; e = 0; return elseif nargin == 2 if length(x)~=length(n) y = nan; e = 1; end for i=1:length(x) y(i) = x(i)^n(i);

Solution 2 function [y, e] = raise(x,n) y = ones(1,length(x)); if nargin == 1 [y e] = raise(x,2*ones(1,length(x))); return elseif nargin == 2 if length(x)~=length(n) y = NaN; e = 1; end for i=1:length(x) for j=1:n(i) y(i) = y(i)*x(i); e = 0;

Getting Help Help and Documentation Digital Hard Copy Accessible Help from the Matlab Start Menu Updated online help from the Matlab Mathworks website: http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.html Matlab command prompt function lookup Built in Demo’s Websites Hard Copy Books, Guides, Reference The Student Edition of Matlab pub. Mathworks Inc.