COMS 3101 Programming Languages: MATLAB. Lecture 2

Similar documents
COMS 3101 Programming Languages: MATLAB. Lecture 3

W1005 Intro to CS and Programming in MATLAB. Data Structures. Fall 2014 Instructor: Ilia Vovsha. hep://

Spring 2010 Instructor: Michele Merler.

W1005 Intro to CS and Programming in MATLAB. MATLAB Basics. Fall 2014 Instructor: Ilia Vovsha. hcp://

Matlab Programming Arrays and Scripts 1 2

Beyond the Mouse A Short Course on Programming

Chapter 3: Programming with MATLAB

5. MATLAB I/O 1. Beyond the Mouse GEOS 436/636 Jeff Freymueller, Sep 26, The Uncomfortable Truths Well, hop://xkcd.com/568 (April 13, 2009)

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

Programming 1. Script files. help cd Example:

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

h"p://bioinfo.umassmed.edu/bootstrappers/bootstrappers- courses/python1/index.html Amp III S6-102

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

Fö 6: Filhantering. DN1212 Numeriska metoder och grundläggande programmering. Pawel Herman. KTH/CB

Introduction to Matlab

Programming in Mathematics. Mili I. Shah

EL2310 Scientific Programming

Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999

Chemical Engineering 541

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

Introduction to Matlab

Computational Methods of Scientific Programming

Getting To Know Matlab

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

EL2310 Scientific Programming

Outline. User-based knn Algorithm Basics of Matlab Control Structures Scripts and Functions Help

MATLAB GUIDE UMD PHYS401 SPRING 2011

CS 61C: Great Ideas in Computer Architecture (Machine Structures) Thread- Level Parallelism (TLP) and OpenMP. Serializes the execunon of a thread

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

Importing and Exporting Data

Introduction to MATLAB

Introduction to Matlab

MATLAB Second Seminar

Digital Image Processing

7 Control Structures, Logical Statements

Practice Reading for Loops

MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB

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

Image Processing CS 6640 : An Introduction to MATLAB Basics Bo Wang and Avantika Vardhan

Basic Plotting. All plotting commands have similar interface: Most commonly used plotting commands include the following.

MATLAB Introduction to MATLAB Programming

CSE 123. Lecture 9. Formatted. Input/Output Operations

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

User Defined Functions

Flow Control and Functions

MATLAB User-defined functions, Data Input/Output. Edited by Péter Vass

ES 117. Formatted Input/Output Operations

Desktop Command window

10 M-File Programming

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

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Introduction to MATLAB

MATLAB GUIDE UMD PHYS375 FALL 2010

Lesson 2 Characteristics of Good Code Writing (* acknowledgements to Dr. G. Spinelli, New Mexico Tech, for a substantial portion of this lesson)

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

ENG Introduction to Engineering

Working with Excel Files. a = round(rand(5,3)*100) xlswrite('rand.xlsx',a) b = xlsread('rand.xlsx')

Question Points Score Total 100

Matlab Primer. Lecture 02a Optical Sciences 330 Physical Optics II William J. Dallas January 12, 2005

MATLAB TUTORIAL WORKSHEET

Clustering Documents. Document Retrieval. Case Study 2: Document Retrieval

Physics 326 Matlab Primer. A Matlab Primer. See the file basics.m, which contains much of the following.

MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB

Pace University. Fundamental Concepts of CS121 1

Introduction and MATLAB Basics

Chapter 6 User-Defined Functions. dr.dcd.h CS 101 /SJC 5th Edition 1

An Introductory Tutorial on Matlab

Using files. Computer Programming for Engineers (2014 Spring)

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

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline

COMS 3101 Programming Languages: MATLAB. Lecture 5

Information for Candidates. Test Format

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

Matlab programming, plotting and data handling

MATLAB for Image Processing. April 2018 Rod Dockter

Computer Vision. Matlab

Introduction to Matlab/Octave

Matlab. Carlo Tomasi. Since images are matrices of numbers, many vision algorithms are naturally implemented

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop:

Lecture 2: Variables, Vectors and Matrices in MATLAB

An Introduction to MATLAB

Some elements for Matlab programming

MATLAB for Image Processing

CpSc 1111 Lab 9 2-D Arrays

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

Introduction to MATLAB

STAT 391 Handout 1 Making Plots with Matlab Mar 26, 2006

Lecture 7. MATLAB and Numerical Analysis (4)

PROGRAMMING WITH MATLAB WEEK 13

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

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Chapter 11 Input/Output (I/O) Functions

Introduction to programming in MATLAB

LECTURE 1. What Is Matlab? Matlab Windows. Help

MATLAB Part 1. Introduction

Introduction to MATLAB

PART 2 DEVELOPING M-FILES

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

4.0 Programming with MATLAB

Transcription:

COMS 3101 Programming Languages: MATLAB Lecture 2 Fall 2013 Instructor: Ilia Vovsha hbp://www.cs.columbia.edu/~vovsha/coms3101/matlab

Lecture Outline Quick review of array manipulanon Control flow Simple scripts and funcnons Loading and saving data GeneraNng simple plots and curves Solve toy problems in class 2.2

Useful Commands why fliplr() reshape(), repmat() Can have mulnple statements on the same line: x = 5; y= 7; help stats for stansncs toolbox 2.3

Array ManipulaNon Special funcnons for arrays: sum(), prod(), mean(), max(), min() First argument we pass to each funcnon is the array What if array is a matrix, what does sum(x) mean? Useful rounnes: sort(), find(), sortrows(), any() Same issue as above, what does sort a matrix mean? 2.4

Array ManipulaNon Special funcnons for arrays: sum(), prod(), mean(), max(), min() Suppose M is a matrix, then: TScol = sum(m); TScol is a row vector, each element is the column sum TSrow = sum(m,2); TSrow is a column vector, each element is the row sum TS = sum(sum(m)); TS is the total sum of all elements in the matrix Can also obtain the locanon of the max/min value (if argument is a vector): [val, loc] = min(m); 2.5

Array ManipulaNon Useful rounnes: sort(), find(), sortrows(), any() FuncNon sort() sorts elements in ascending (default) order. Can specify the order explicitly: sort_list = sort(m, descend ); If M is a matrix, sorts each column independently As above, can sort across columns: sort(m,2, ascend ) If consistency between rows is required, use sortrows() 2.6

Array ManipulaNon FuncNon find() returns indices of elements which sansfy some condinon: find(m) Return indices of nonzero elements of M (default) find(m == 1) Return indices of elements of M equal to one find(m >= 2 & M < 6) Return indices that sansfy both condinons If M is a matrix, the returned index is a single value which is a bit annoying. SoluNon: use ind2sub(), sub2ind() to convert between indices [r,c] = ind2sub(size(m),index) 2.7

Scripts MATLAB specific script files (M files) Files have the extension.m (example: test.m) To run your script just type test in the command line A script is a list of commands that should be executed To pass arguments to the script we will use funcnons (more on that later) 2.8

Comments Comments make the code more manageable Can add a one line comment by using the % symbol: % this is a comment Anything that follows a % is ignored by the compiler (not executed) When you type help <func_name> you get the comments at the top of the <func_name> script Can also use block comments: %{. %} 2.9

Debugging Debugging is the proper way of tracking program execunon and fixing errors Type help debug or use debug from the workspace menu Simple alternanve: pause() funcnon pause(): halt program unnl user strikes any key pause(n): halt program for n seconds Approach: add output statements followed by pause() to follow progress 2.10

Control Flow Without flow, the scripts have no life In general: a control flow statement begins with some keyword and ends with the keyword end General Form (if): if (condinonal statement) body end Example: if x == 1 y = 5; end 2.11

Control Flow Cond. Statement General Form (if): if (condinonal statement) body end CondiNonal statements can be with or without () Typically use logical and relanonal operators in the condinon: (OR), & (and), ~ (NOT) Good idea to use () when the statement is a long one AlternaNve: define a variable in the previous line T = (x == 2 y == 3) & x > 5; if (T) 2.12

Control Flow General Form (if else): if (condinonal statement) body1 else body2 end Example: if x == 1 y = 5; else y = 2; end 2.13

Control Flow General Form (if elseif): if (cond. statement1) body1 elseif (cond. statement 2) body2 else body3 end Example: if x == 1 y = 5; elseif x == 2 y = 3; else y = 2; end 2.14

Control Flow Loops Used for repennon General Form (for): for (iteranon variable) body1 end NoNce how the iteranon variable is iterated over a row vector Example: for i = 1:5 disp(i+1); end 2.15

Control Flow Loops General Form (while): while (cond. statement) body1 end Example: x = 0; while x < 5 x = x + 1; disp(x); end 2.16

Control Flow Loops Example (connnue): y = 0; for x = 1:10 if (x == 3); connnue; end y = y +1; end What is y =? Example (break): y = 0; for x = 1:10 if (x == 3); break; end y = y +1; end What is y =? 2.17

Control Flow Caveat Loops are extremely inefficient in MATLAB, avoid them like the plague! AlternaNves? Built in funcnons (find, sort, rand) Pre allocate memory (ininalize array before entering loop) 2.18

Exercise (In Class) Control flow & array manipulanon Write a script that takes two (hard coded) vectors {A,B}. For every element of A, print the element of B at the corresponding index (index = element of A). At the end of the procedure, print the sum and product of the printed elements 2.19

FuncNons DefiniNon The keyword is funcnon. There are mulnple ways of defining funcnons: funcnon < name > ( <var>) funcnon < name > ( <var1>, <var2>) funcnon < out_var > = <name> ( <var>) funcnon [ <out_var1>, <out_var2>] = <name> ( <var1>,<var2>) The body of a funcnon is just a set of statements (no different from a script) You can use the keyword end to terminate a funcnon, but this is not required 2.20

FuncNons DefiniNon It is possible to have a variable number of (input or output) arguments: funcnon < name > ( <var>, varargin) funcnon [ <out_var1>, varargout] = <name> ( <var1>,<var2>) varargin, varargout are cell arrays (we discuss these later). You can check the number of declared input arguments for the funcnon using nargin, nargout: Example: nargin( mean ) 2.21

FuncNons Example funcnon wakeup(n) if N > 10 pause(n); disp( Alarm ); end funcnon s = total(a, B) if length(a) == length(b) s = A + B; else s = A(1) + B(1); end 2.22

FuncNons SubfuncNons Typically one funcnon for one file (file name = funcnon name) Also possible to include mulnple funcnons in one file: Main funcnon and sub funcnons Sub funcnons are only visible to other funcnons in the same file Useful when you have many minor and very specific rounnes Type help funcnon to see an example 2.23

Exercise (In Class) FuncNons & matrix manipulanon Suppose M is a {0,1} matrix that represents a directed graph. If M(i,j) = 1, then there exists a directed edge from i to j. Write a funcnon that takes M as input, and (for every edge) prints the word edge followed by the vernces of the edge. The funcnon should return the total number of edges in the graph in the variable T 2.24

Input / Output sprin() sprin() converts (formats) data into a string: Example: S = sprin( myfile%d, 2); The character following % specifies the format into which the supplied parameter is converted Can specify different formats and supply mulnple parameters Example: S = sprin( myfile%d%s, 2, test ); Common formats: %d (integer) %s (string) %g (float) Example: 1. prefix = home_dir/mydata ; 2. file_num = 2; 3. filename = sprin( %s%d.txt, prefix, file_num); 2.25

I/O Formats format <type> : Controls output formats, and has no effect on computanon For beber appearance of numbers with many decimal digits use format short g To remove annoying spaces (line feeds) use format compact Possible to specify mulnple formats as long as they don t contradict each other 2.26

I/O User Input input() is a command that prompts the user to enter some input To record the input, you need to supply a variable The input stream is closed when the user hits enter By default, the expected input is a MATLAB expression Examples: color = input( Enter your choice ); color = input( Enter your choice, s ); color = input( Enter your choice\n, s ); 2.27

I/O MATLAB Data MATLAB has its own file extension.mat A.mat file is stored in binary format (unlike say text files it is pointless to view a.mat file) Storing data in a.mat file is convenient: Can load and save data using built in commands Can load/save specific variables to/from the workspace Examples (load): load file1; % AutomaNcally checks for file1.mat and loads all vars v1 = load( file1.mat, X); % Loads the variable X from file1.mat 2.28

I/O MATLAB Data Examples (save): save file1.mat X; % Save variable X to file1.mat save(filename, X ); % Save X to a file whose name is stored in the variable filename save file1.mat X Y Z; % Save X, Y, Z to file1.mat 2.29

I/O Text Files Commands: fopen(), fclose(), fgetl(), fseek(), fprin() More complex than loading.mat files. First need to open a file fopen(), then read/write the data fgetl(), fprin(), then close the file fclose() To open a file, we create a file idennfier : FID = fopen( myfile.text, r ); % 2 nd argument specifies operanon r (read), w (write), a (append) In case of failure, FID = 1 Always check whether file was opened 2.30

I/O Text Files To close a file is easy: FID = fopen( myfile.text, r ); SOPEN = fclose(fid); % returns 1 if failed to close Read a line from a file: myline = fgetl(fid); % Read a single line Rewind file: fseek(fid,0, 1); % O en necessary to traverse a file mulnple Nmes Write to a file: fprin() writes formabed data to file fprin(fid, FORMAT, ARRAY); % Format is a string 2.31

I/O Text Files Typically files have a specific format: numeric data separated by some delimiter (a character) MATLAB has built in funcnons: dlmread(), dlmwrite() Examples: M = dlmread( file1.txt, \t ) % Read tab delimited data into M Choose any character(s) as your delimiter. Be wary of spaces or dots as delimiters M = dlmread( file1.txt, ;, [R1 C1 R2 C2] ) % 3 rd parameter is the range (zero based) from which the data is read dlmwrite( file1.txt', M, \t ) % Write M to a tab delimited file 2.32

I/O Images Image are just matrices. Color images have an addinonal dimension (B,G,R values). Grayscale images just have pixel values Built in commands: imread(), imwrite() Examples: M = imread( myphoto.jpg ); % Read an image imwrite(m, myphoto,jpg ); % Infers the format from the ext. imwrite(m, myphoto, JPEG ); 2.33

Exercise (In Class) Loading and saving a sequence of files. Suppose you have a directory home/mydata which contains 100 files all named dataset_#.mat. Each files stores a matrix M. Write a funcnon that takes an input parameter N, and opens each file (from 1 to N), sorts the matrix M in row order, and save the sorted matrix to a new file named newdata_#.mat 2.34