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.

Slides:



Advertisements
Similar presentations
Shell Scripting Printing; Loops and Logic printf: formatted print printf is a more standardized method to print text to the screen. It can be used instead.
Advertisements

Lecture 5.
COMP 116: Introduction to Scientific Programming Lecture 37: Final Review.
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
Programming with MATLAB
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Computer Science in Practice This course is an introduction to problems (and solutions) that arise in applied fields of computer science such as machine.
General Computer Science for Engineers CISC 106 Lecture 08 Dr. John Cavazos Computer and Information Sciences 2/27/2009.
Getting started with Matlab Numerical Methods Appendix B help/techdoc/learn_matlab/learn_matlab.html.
Programming in MATLAB Week 14 – 4/28/09 Kate Musgrave
C ENTER FOR I NTEGRATED R ESEARCH C OMPUTING MATLAB
Shell Programming 1. Understanding Unix shell programming language: A. It has features of high-level languages. B. Convenient to do the programming. C.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
What is MATLAB ? MATrix LABratory –Originally, it was a front-end to FORTRAN matrix routines developed in the U. of New Mexico and Stanford –Today.
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.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Introduction to MATLAB. Windows in MATLAB Command Window – where you enter data, run MATLAB code, and display results Command History - displays a log.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 6.
How to think through your program [ principles of good program design ] Rachel Denison MATLAB for Cognitive Neuroscience ICN, 13 December 2007.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
Selection Programming EE 100. Outline introduction Relational and Logical Operators Flow Control Loops Update Processes.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.
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.
CS 170 – INTRO TO SCIENTIFIC AND ENGINEERING PROGRAMMING.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
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 Programming COMM2M Harry R. Erwin, PhD University of Sunderland.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
Matlab Programming a logical approach. Outline Announcements: –Homework I: due Wed. by 5, by –Last day to add/drop or change credit/audit Iteration.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
General Computer Science for Engineers CISC 106 Lecture 13 - Midterm Review James Atlas Computer and Information Sciences 10/02/2009.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
CSC 4630 Meeting 17 March 21, Exam/Quiz Schedule Due to ice, travel, research and other commitments that we all have: –Quiz 2, scheduled for Monday.
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
1 Structured Programming EEN170 Programming in MATLAB.
Flow control. Conditionals if condition do this stuff end if condition do this stuff else do this stuff end if condition do this stuff elseif condition.
Python Simple file reading Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Simple Pythonic file reading Python has a special.
CSC 4630 Meeting 7 February 7, 2007.
EEE 161 Applied Electromagnetics
Matlab Training Session 4: Control, Flow and Functions
Chapter 5 - Control Structures: Part 2
Scripts & Functions Scripts and functions are contained in .m-files
StatLab Matlab Workshop
Lecture 3 MATLAB programming (1)
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Logical Operations In 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 Basics.
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Review The Unix Shells Graham Glass and King Ables,
Presentation transcript:

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 There are two kinds of M-files: Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace. Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.

Functions Functions are M-files that can accept input arguments and return output arguments. Comments in Matlab are denoted using the % symbol.

Note that this loadsac funtion reads a SAC file, sends that file to another function called sac, works with the resulting 4 matrices, and then returns a data matrix, and the 3 scalars dt, beg, pt. functions can call other functions.

How to represent “nothing” Array = [] String = ‘’ Useful for defining a name to be used on Left Hand Side. Size and length are zero.

Elementary matrices zeros - Zeros array. ones - Ones array. eye - Identity matrix. linspace - Linearly spaced vector. logspace - Logarithmically spaced vector. freqspace - Frequency spacing for frequency response. meshgrid - X and Y arrays for 3-D plots. accumarray - Construct an array with accumulation. : - Regularly spaced vector and index into matrix. Basic array information. size - Size of array.

Some unix commands (pwd, ls, ???) “work” in matlab (they are actually matlab commands) a=pwd; b=ls; Some matlab commands have the same names as unix commands, but are not the same “cat” is a matlab command that concatenates matrices (not files) Matlab does not pass things it does not understand to the OS to see if they are OS commands.

Relational Operators Returns 1 if true and 0 if false All relational operators are left to right associative These are element-by-element comparisons < : test for less than <= : test for less than or equal to > : test for greater than >= : test for greater than or equal to == : test for equal to ~= : test for not equal

Relational Operators with matrices Relational operators may not behave like you think with matrices, so be careful. Some useful relational operators for matrices include the following commands: isequal : tests for equality isempty: tests if an array is empty all : tests if all elements are nonzero any: tests if any elements are a nonzero; ignores NAN These return 1 if true and 0 if false

Logical Operators Logical array operators return 1 for true and 0 for false Work element-by-element & : logical AND; tests that both expressions are true | : logical OR ; tests that one or both of the expressions are true ~ : logical NOT; tests that expression is true

Logical Operators w/ Short- circuiting If the first tested expression will automatically cause the logical operator to fail, the remainder of the expression is not evaluated. && : short-circuit logical AND || : short-circuit logical OR (b ~= 0) && (a/b > 18.5) if (b ~= 0) evaluates to false, MATLAB assumes the entire expression to be false and terminates its evaluation of the expression early. This avoids the warning that would be generated if MATLAB were to evaluate the operand on the right.

if/elseif/else/end If expression is true, then run the first set of commands. Else if a second expression is true, run the second set of commands. Else if neither is true, run a third set of commands. End the if command if rem(n,2) ~= 0%calculates remainder of n/2 M = odd_magic(n) elseif rem(n,4) ~= 0 % ~= is ‘not equal to’ test M = single_even_magic(n) else M = double_even_magic(n) end

Checking for special elements (NaN, Inf) isnan(a) Returns 1 for every NaN in array a. isinf(a) Returns 1 for every Inf in array a. isfinite(a) Returns 1 for every finite number (not a (Nan or Inf)) in array a. isreal(a) Returns 1 for every non-complex number array a.

Using special elements to your advantage. Since NaNs propagate through calculations (answer is NaN if there is a NaN somewhere in the calculation), it is sometimes useful to throw NaNs out of operations like taking the mean. (A handy trick to ignore stuff you don’t want while you continue calculating.) So the function that identifies NaNs can be very useful: ix=find(˜isnan(a)); m=mean(a(ix)); this finds all values that are not NaNs and averages them.

switch, case, and otherwise switch executes the statements associated with the first case where switch_expr == case_expr If no case expression matches the switch expression, then control passes to the otherwise case (if it exists). switch switch_expr case case_expr statement,..., statement otherwise statement,..., statement end

for one of the most common loop structures is the for loop, which iterates over an array of objects for x values in array, do this for m = 1:x for n = 1:y h(m,n) = 1/(m+n); end * Try to avoid using i and j as loop counters (matlab uses them for sqrt(-1) )

while/end while: continues to loop as long as condition exited successfully n= 1; while (1+n) > 1, n= n/2;, end n= n*2 * in the simple example above, I used the “,” rather than a newline to separate the parts of this loop. This can be done with any type of loop structure.

break break: allows you to break out of a for or while loop exits only from the loop in which it occurs while condition1 # Outer loop while condition2 # Inner loop break # Break out of inner loop only end... # Execution continues here after break end

continue continue: pass control to next iteration of for or while loop passes to the next iteration of the loop in which it occurs fid = fopen('magic.m','r'); count = 0; while ~feof(fid) line = fgetl(fid); if isempty(line) | strncmp(line,'%',1) continue end count = count + 1; end disp(sprintf('%d lines',count));

return return: returns to invoking function allows for termination of program before it runs to completion %det(magic) function d = det(A) %DET det(A) is the determinant of A. if isempty(A) d = 1; return%exit the function det at this point else... end

Multidimensional Arrays Arrays with more than two subscripts >>p = perms(1:4); >>A = magic(4); >>M = zeros(4,4,24); >>for k = 1:24 M(:,:,k) = A(:,p(k,:)); end