Introduction to Matlab & Data Analysis

Slides:



Advertisements
Similar presentations
Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
Advertisements

A MATLAB function is a special type of M-file that runs in its own independent workspace. It receives input data through an input argument list, and returns.
Zhang Hongyi CSCI2100B Data Structures Tutorial 2
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 19P. 1Winter Quarter MATLAB: Script and.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
The IDE (Integrated Development Environment) provides a DEBUGGER for locating and correcting errors in program logic (logic errors not syntax errors) The.
General Computer Science for Engineers CISC 106 Lecture 08 Dr. John Cavazos Computer and Information Sciences 2/27/2009.
1 Gentle Introduction to Programming Tirgul 1: Shell and Scala “hands on” in the lab.
Division Example 2x - 3y + 4z = 10 x + 6y - 3z = 4 -5x + y + 2z = 3 A*X = B where A = B = >> X = A\B X =
1 CSE1301 Computer Programming: Lecture 25 Software Engineering 2.
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.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
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.
IE 212: Computational Methods for Industrial Engineering
1 Web-Enabled Decision Support Systems Objects and Procedures Don McLaughlin IE 423 Design of Decision Support Systems (304)
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Introduction to Matlab & Data Analysis
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
Chapter 3 (Part 3): Mathematical Reasoning, Induction & Recursion  Recursive Algorithms (3.5)  Program Correctness (3.6)
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
Matlab Programming for Engineers Dr. Nidal Farhat Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
Introduction to Engineering MATLAB – 6 Script Files - 1 Agenda Script files.
Matlab Workshop 1/10/07 Lesson 1: Matlab as a graphing calculator.
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.
Function M-File Numerical Computing with. MATLAB for Scientists and Engineers.
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.
1 Flow of control Sequential Executing instructions one by one, in exact order given Selection Choosing to execute a particular set of statements depending.
Functions CS 103 March 3, Review A function is a set of code we can execute on command to perform a specific task A function is a set of code we.
Functions CS 103. Review A function is a set of code we can execute on command to perform a specific task When we call a function, we can pass arguments.
Practice and Evaluation. Practice Develop a java class called: SumCalculator.java which computes a sum of all integer from 1 to 100 and displays the result.
CMPS 1371 Introduction to Computing for Engineers MatLab.
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.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
COMP 116: Introduction to Scientific Programming Lecture 11: Functions.
1 Programming with MATLAB ผศ. ดร. อนันต์ ผลเพิ่ม Anan Phonphoem
Structured Programming: Debugging and Practice by the end of this class you should be able to: debug a program using echo printing debug a program using.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
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.
Testing Chapter 23 IB103 Week 12 (part 3). Verify that a complex (any) program works correctly, that the program meets specifications The chapter reviews.
General Computer Science for Engineers CISC 106 Lecture 13 - Midterm Review James Atlas Computer and Information Sciences 10/02/2009.
Introduction to Computer Programming - Project 2 Intro to Digital Technology.
CompSci 100E 18.1 Testing and Debugging Robert A Wagner.
The Department of Engineering Science The University of Auckland Welcome to ENGGEN 131 Engineering Computation and Software Development Lecture 2 Debugging,
CSE 455 : Computer Vision MATLAB 101 Getting Started with MATLAB.
Debugging tools in Flash CIS 126. Debugging Flash provides several tools for testing ActionScript in your SWF files. –The Debugger, lets you find errors.
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
ESC101: Introduction to Computing
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Matlab Training Session 4: Control, Flow and Functions
Eclipse Navigation & Usage.
Scripts & Functions Scripts and functions are contained in .m-files
User Defined Functions
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
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.
ME 123 Computer Applications I Lecture 4: Vectors and Matrices 3/14/03
Presentation transcript:

Introduction to Matlab & Data Analysis Tutorial 7: Functions and Program Design Please change directory to directory E:\Matlab (cd E:\Matlab;) From the course website (http://www.weizmann.ac.il/midrasha/courses/MatlabIntro//course_outline.htm ) Download: playTicTacToe.m , isLegalMove.m , isPlayerWon.m, getNextMove.m, myFactorial.m Weizmann 2010 ©

Goals Top down design Introduction Functions M file structure Functions workspace Functions Input and output Top down design Local functions Debugger Recursion More: Functions and commands Functions and the matlab search path

Function Is an Independent Piece of Code Which Performs a Task Function (subroutine, method, procedure, or subprogram) – is a portion of code within a larger program, which performs a specific task and can be relatively independent of the remaining code. One M-file, One Task, One Workspace

Variables - The Data Objects, Functions Are The Actions Input (Object / Data): X = 80 90 95 100 98 88 92 Functions: y = mean(x) y = sum(x) y = max(x) Output: (Data) 91.85 643 100

A Function Is a Black Box Output Input function A function is a black box It hides the code and its workspace and communicates with the “world” using the input and output variables 5 5

Functions M file structure The file is a Matlab function The output variables (if there are few use []: [out1 out2] ) Should be same as the name of the file sumTwoNums.m: function my_sum = sumTwoNums(a,b) my_sum = a+b; The input variables Assign the output variables (else - Matlab will give an error)

Functions Documentation and Variable Verification function my_sum = sumTwoNums(a,b) % SUMTWONUMS sum to scalars % this function sums two scalar % and returns the result % INPUT: % a - the first scalar % b - the second scalar % % OUTPUT: % my_sum - the sum of a and b; sum = a+b if (~isscalar(a)) error('First argument is not a scalar'); end if (~isscalar(b)) error('Second argument is not a scalar'); my_sum = a+b; First line help: Usage Input Output Examples Testing for proper variables Calculations and Output assignment

Each Instance of A Function Run Has Its Own Workspace Assume we wrote the function: function my_sum = sumTwoNums(a,b) my_sum = a + b; In the workspace we run: a = 1; b = 2; x = 3; y = 4; s = sumTwoNums(x, y) What is the output? s = 7 Matlab Workspace: a = 1 b = 2 X = 3 y = 4 s = 7 Function Workspace: a = 3 b = 4 my_sum = 7

Matlab Functions Can Be Called With Fewer Input Arguments Than Specified Consider a function that computes function y = calSecondOrderPoly(x, a, b, c) switch nargin case 4 % do nothing case 3 c = 0; case 2 b = 0; otherwise error('Incorrect input'); end y = a*x.^2 + b*x + c; Switch according to input arguments number Default value

Matlab Functions Can Be Called With Fewer Output Arguments Than Specified Recall: [r,c] = find(A) , ind = find(A); sorted_A= sort(A); [sorted_A, sort_ind] = sort(A); Now lets improve our function such that if it called with two output arguments, the second argument is the derivative: [y, y_derivative] = calSecondOrderPoly(x, a, b, c);

Matlab Functions Can Be Called With Fewer Output Arguments Than Specified function [y, y_derivative] = calSecondOrderPoly(x, a, b, c) y = a*x.^2 + b*x + c; if nargout == 2 y_derivative = 2*a*x + b; end Checks number of output arguments Can help avoid expensive computations when they are not necessary

Example - Write a function subtractTwoNums Add Help to the function Input: a, b Output: a-b Add Help to the function Try calling the function (Debugger) *Extra: if the function needs to return two output variables: Output: [a-b, b-a]

Top Down Design A method to solve complex problems Principles: Start from large problems to small A function does one task Think before you code

Top Down Design and Debugging – Tic-Tac-Toe Example Problem specifications: Build a tic-tac-toe game for two players.

Lets break the problem top-down Play Tic-Tac-Toe Have some game matrix Get Next Move Check for a winner Initiate the game matrix Get column Get row Announce the winner Update the game matrix Check whether the move is legal Display the game matrix

Choosing the Data Structures We will use two game matrices Warning: We use it here for simplicity, usually it is better to avoid data duplication “Num_mat” - 3x3 numeric matrix “display_mat” - 3x9 char matrix 1 NaN 2 ‘ X ‘ ‘ – ‘ ‘ O ‘

Writing the functions – “Go with the (control) flow” Play Tic-Tac-Toe Initiate game matrix Initiate “who won flag” variable to 0 Initiate “current player flag” variable to 1 Loop 9 times (for i=1:9): Get Next Move Update game matrix Display game matrix Check for winner – if found a winner: Update “who won flag” (1 or 2) and Break Switch the “current player flag” 1<->2 Announce winner according to the “who won flag” variable A “Flags” – A variable which holds information about the program status and helps you control the flow Get row Get column Check if it is a legal move

Lets look at the code of the main function: edit playTicTacToe Lets look at the code of the main function: edit playTicTacToe.m; Notice the local functions Weizmann 2010 ©

Debugging Run Time Errors Our weapons: Break points – Red Gray Modifying a file Debug buttons Debug menu Stop if errors / warn There are two bugs Lets find them . . To the code!

Error Syntax errors – Runtime errors – Lets try to run playTicTacToe func1; function func1() func2() Syntax errors – Lets try to run playTicTacToe Runtime errors – You can plant in the code disp() massages that will help you debug. You should use errors when the input of the function is not valid Debugger … function func2() Try func3(); Catch disp(‘Caught’); end function func3() func4() function func4 () A = ones(1,1); B = A(1,2);

Recursion – factorial example I don’t know what is factorial of 3 But I know it is 3 multiply the factorial of 2 function res = myFactorial(x) % check: x is a non-negative integer if (x == 0 || x == 1) res = 1; else res = x * myFactorial(x-1); end I don’t know what is factorial of 2 But I know it is 2 multiply the factorial of 1 Ah ha! The factorial of 1 is 1!

Summary Top down design Introduction Functions M file structure Functions workspace Functions Input and output Top down design Local functions Debugger Recursion More: Functions and commands Functions and the matlab search path